{"id":11191,"date":"2020-08-30T15:00:06","date_gmt":"2020-08-30T13:00:06","guid":{"rendered":"https:\/\/qodeinteractive.com\/magazine\/?p=11191"},"modified":"2021-04-22T10:31:08","modified_gmt":"2021-04-22T08:31:08","slug":"create-shortcode-in-wordpress","status":"publish","type":"post","link":"https:\/\/qodeinteractive.com\/magazine\/create-shortcode-in-wordpress\/","title":{"rendered":"How to Create a Custom Shortcode in WordPress"},"content":{"rendered":"<div class=\"wpb-content-wrapper\"><p>[vc_row][vc_column][vc_column_text]Ever since the release of WordPress 2.5 shortcodes have been the preferred way of adding custom features and functionalities among plugin and theme developers. By using shortcodes you can add sliders, image galleries, buttons, custom font text, contact forms, and so much more. Despite being very powerful, shortcodes weren\u2019t known for being beginner-friendly, unless they were integrated inside some of the newer and more popular page builders, like Elementor or WPBakery. As such, we are pretty sure most of our readers have already used shortcodes but probably never ventured into creating their own.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Even though coding can seem intimidating to most, the process of creating a shortcode is a lot easier than it seems at first glance. For that reason, we decided to create this article and explain the process in depth. In the sections to come, we will clear up exactly what shortcodes are, how to create them using examples that vary in difficulty, as well as how to use them on various parts of your website. Before we start, we must mention that, depending on your previous WordPress knowledge, additional research might be needed to follow along with and understand the topics discussed. In case you want to, you can use the links below to skip to different parts of this article:<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;22px&#8221;]<ul class=\"qodef-unordered-list-item qodef-toc\">\n    <li>\n\t        <div class=\"qodef-ul-title-holder\">\n            <span class=\"qodef-ul-title-content\"><a href=\"#creating-custom-shortcodes\">Creating custom shortcodes<\/a><\/span>        <\/div>\n            <\/li>\n<\/ul>[vc_empty_space height=&#8221;5px&#8221;]<ul class=\"qodef-unordered-list-item qodef-toc\">\n    <li>\n\t        <div class=\"qodef-ul-title-holder\">\n            <span class=\"qodef-ul-title-content\"><a href=\"#examples-of-custom-shortcodes\">Examples of custom shortcodes<\/a><\/span>        <\/div>\n            <\/li>\n<\/ul>[vc_empty_space height=&#8221;5px&#8221;]<ul class=\"qodef-unordered-list-item qodef-toc\">\n    <li>\n\t        <div class=\"qodef-ul-title-holder\">\n            <span class=\"qodef-ul-title-content\"><a href=\"#using-custom-shortcodes\">Using custom shortcodes<\/a><\/span>        <\/div>\n            <\/li>\n<\/ul>[vc_empty_space height=&#8221;5px&#8221;]<ul class=\"qodef-unordered-list-item qodef-toc\">\n    <li>\n\t        <div class=\"qodef-ul-title-holder\">\n            <span class=\"qodef-ul-title-content\"><a href=\"#additional-tips\">Additional tips<\/a><\/span>        <\/div>\n            <\/li>\n<\/ul>[vc_empty_space height=&#8221;70px&#8221;][\/vc_column][\/vc_row][vc_row][vc_column][vc_column_text]<\/p>\n<h2 class=\"qodef-h4\">Understanding what custom shortcodes are<\/h2>\n<p>[\/vc_column_text][vc_column_text]WordPress shortcodes are simple code shortcuts, defined with square brackets (such as [shortcode_name]), that perform a predefined function or a set of functions. Depending on the function(s) used, the purpose of a shortcode could be something as small as adding a \u201cHello world\u201d text or something as substantial as building the content of an entire webpage.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]You can classify shortcodes in several different ways. WordPress, by default, has <a href=\"https:\/\/developer.wordpress.org\/plugins\/shortcodes\/\" target=\"_blank\" rel=\"noopener noreferrer\">six built-in shortcodes<\/a>: <strong>[ caption ]<\/strong>, <strong>[ gallery ]<\/strong>, <strong>[ audio ]<\/strong>, <strong>[ video ]<\/strong>, <strong>[ playlist ]<\/strong> and <strong>[ embed ]<\/strong>. As those shortcode names are quite self-explanatory, we won\u2019t delve into them at this time. Any other shortcode, created by plugin or theme developers, or yourself, is referred to as a custom one. Another way to classify shortcodes is based on whether the associated function accepts parameters or not. However, they are most often divided into two types: <strong>self-closing shortcodes<\/strong> and <strong>enclosing shortcodes<\/strong>, based on how you use them. The self-closing shortcodes use only the opening shortcode tag. On the other hand, the enclosing shortcodes require a closing tag as well as the opening one since they utilize the content inserted between those two tags. In practice, they look something like this:[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]<strong>[shortcode_name] \u2013 self-closing shortcode<\/strong>[\/vc_column_text][vc_column_text]<strong>[shortcode_name]Additional content used in the shortcode[\/shortcode_name] \u2013 enclosing shortcode<\/strong>[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]In most cases, both types of shortcodes accept parameters defined within the corresponding functions, as you will be able to see from the examples we included in the following section.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;68px&#8221;][\/vc_column][\/vc_row][vc_row][vc_column][vc_column_text]<\/p>\n<h2 class=\"qodef-h4\"><a id=\"creating-custom-shortcodes\"><\/a>Creating custom shortcodes<\/h2>\n<p>[\/vc_column_text][vc_column_text]WordPress\u2019 <a href=\"https:\/\/codex.wordpress.org\/Shortcode_API\" target=\"_blank\" rel=\"noopener noreferrer\">Shortcode API<\/a> represents a set of functions that allow a shortcode to be registered, as well as to fetch and parse supplied attributes. Also, while processing a page or post, any registered shortcode tags are replaced with the corresponding output, thanks to the Shortcode API. Therefore, before we delve into creating any specific shortcodes, it is important to understand how to register a shortcode.[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]To register a shortcode, you have to use the <a href=\"https:\/\/developer.wordpress.org\/reference\/functions\/add_shortcode\/\" target=\"_blank\" rel=\"noopener noreferrer\">add_shortcode<\/a> function. The function has two parameters. The first is a unique shortcode tag that represents the name of the shortcode. The second is the name of the handler function (or callback, as it is better known) that is executed after the shortcode is registered. You can see how this code would look like in the example given below:[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">add_shortcode( 'shortcode_name', 'handler_function_name' );<\/pre>\n<p>[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]To clarify, <strong>shortcode_name<\/strong> is the unique shortcode tag, while the <strong>handler_function_name<\/strong> is the callback function name.[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]However, registering a shortcode isn\u2019t enough. You need to take one more step, and that is writing the handler function. This function gives your shortcode its purpose.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Here\u2019s a generalized example of the registration of a shortcode and the addition of its corresponding handler function.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">function handler_function_name( $atts, $content, $shortcode_tag ){\r\n\/\/ Some code goes here\r\n}\r\nadd_shortcode( 'shortcode_name', 'handler_function_name' );<\/pre>\n<p>[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Let us explain this code block in detail.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]The name of the callback has to match the second argument of the add_shortcode function (<strong>handler_function_name<\/strong> in our example).[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Additionally, the callback accepts up to three parameters. The <strong>$atts<\/strong> variable represents <strong>an <a href=\"https:\/\/www.php.net\/manual\/en\/language.types.array.php\" target=\"_blank\" rel=\"noopener noreferrer\">associative array<\/a> of attributes<\/strong> that are passed to the function. This parameter can be omitted if you choose to write a shortcode that doesn\u2019t accept user-inserted attributes. The <strong>$content<\/strong> variable is reserved for enclosing type shortcodes, as it <strong>represents the content a user inserts between the opening and closing tags of a shortcode<\/strong>. This variable would correspond to the part with <strong>this is the user-inserted content<\/strong> in the example given below.[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">[shortcode_name]this is the user-inserted content[\/shortcode_name]<\/pre>\n<p>[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Of course, if you decide to create a self-closing shortcode, this parameter should be omitted.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]As for the last parameter, the <strong>$shortcode_tag<\/strong> variable represents the shortcode tag, which is the name of the shortcode itself. It is the part with <strong>shortcode_name<\/strong> in our example. Of the three parameters, because it is rarely needed, $shortcode_tag is omitted the most. It is only required when two registered shortcodes share the same callback function.[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Finally, the part of the code denoted by the comment <strong>\/\/ Some code goes here<\/strong> is where you should add the code that enables a new feature. Simply replace the comment with your code.[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Now that you know what each part of the code does, we can proceed to the examples. You can refer back to this section if at any point you need a reminder of the details of shortcode registration or handler functions and its properties. Additionally, if you want to speed up the process of creating a shortcode, you can try using a <a href=\"https:\/\/generatewp.com\/shortcodes\/\" target=\"_blank\" rel=\"noopener noreferrer\">shortcode generator<\/a>. It will help you get a baseline code similar to the one given in our example above so you can build on that.[\/vc_column_text][vc_empty_space height=&#8221;80px&#8221;][vc_widget_sidebar sidebar_id=&#8221;new-top-picks-banner&#8221;][vc_empty_space height=&#8221;81px&#8221;][\/vc_column][\/vc_row][vc_row][vc_column][vc_column_text]<\/p>\n<h2 class=\"qodef-h4\"><a id=\"examples-of-custom-shortcodes\"><\/a>Examples of custom shortcodes<\/h2>\n<p>[\/vc_column_text][vc_column_text]In the following section, we will show and carefully explain three different shortcode examples. Even though the examples vary in difficulty, the one thing they have in common is the return statement. The return tag is mandatory when creating shortcodes, as the return output is what replaces the shortcode tag ([shortcode_name]) when it is used. We will talk in more depth about the use of the shortcodes in the section that comes after this one.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]What we strongly suggest, before you try to create a new shortcode, is to <a href=\"https:\/\/qodeinteractive.com\/magazine\/how-to-manually-backup-wordpress-website\/\">backup your website<\/a>. Any mistake, especially one in syntax, may break your website. As soon as you\u2019ve done that, you can turn to shortcode creation.[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]You can add the code shown in this section into <strong>the functions.php file<\/strong> of your theme. However, it is better if you place the code into a separate file or even create a custom plugin for it. We will touch upon this topic later, as part of the additional tips section.[\/vc_column_text][vc_empty_space height=&#8221;72px&#8221;][vc_column_text]<\/p>\n<h3 class=\"qodef-h5\">Example 1:<\/h3>\n<p>[\/vc_column_text][vc_column_text]The most basic example of a shortcode is a <strong>self-closing shortcode without parameters<\/strong>. As explained above, the name of the handler function and the second argument of the add_shortcode function have to be the same. Furthermore, the first argument of that same function determines how we use the shortcode, while <a href=\"https:\/\/www.php.net\/manual\/en\/language.types.string.php\" target=\"_blank\" rel=\"noopener noreferrer\">the string<\/a> after the return tag determines what you will see on the screen. <a href=\"https:\/\/www.php.net\/manual\/en\/function.date.php\" target=\"_blank\" rel=\"noopener noreferrer\">The date function<\/a> used in this example returns a date string based on the time format we inserted. The format we used is d-m-Y, standing for day-month-year, expressed numerically in the output. Finally, we have used dots(.), which are string concatenation operators, to join all three strings into one and display it on the webpage.[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Adding a basic custom shortcode that tells the current date\r\nfunction custom_date_shortcode( ) {\r\nreturn '&lt;p&gt;The current date is ' . date('d-m-Y') . '.&lt;\/p&gt;';\r\n}\r\nadd_shortcode( 'current_date', 'custom_date_shortcode' );<\/pre>\n<p>[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]<strong>Please note, we also used comments and indentation to improve code readability. We encourage you to do the same in any custom shortcodes you make.<\/strong> Having said that, here\u2019s how our current date shortcode looks when used on a website.[\/vc_column_text][vc_empty_space height=&#8221;50px&#8221;]<div class=\"qodef-single-image-holder   qodef-has-border \">\n    <div class=\"qodef-si-inner\" >\n                                    <img loading=\"lazy\" decoding=\"async\" width=\"700\" height=\"374\" src=\"https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Current-Date.jpg\" class=\"attachment-full size-full\" alt=\"Current Date\" srcset=\"https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Current-Date.jpg 700w, https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Current-Date-300x160.jpg 300w, https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Current-Date-620x331.jpg 620w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/>                        <\/div>\n<\/div>[vc_empty_space height=&#8221;72px&#8221;][vc_column_text]<\/p>\n<h3 class=\"qodef-h5\">Example 2:<\/h3>\n<p>[\/vc_column_text][vc_column_text]A slightly more challenging task is <strong>creating a self-closing shortcode that accepts arguments that a user can insert<\/strong>. To do so, one of the three parameters of a handler function has to be used, in this case, the $atts variable. In the example below, we chose to showcase a very simple, yet instructional shortcode that explains the various phases of shortcode creation.[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Adding a colored text shortcode\r\nfunction custom_colored_text( $atts ) {\r\n$default_atts = array(\r\n\"title\" =&gt; '',\r\n\"title_color\" =&gt; ''\r\n);\r\n$params = shortcode_atts( $default_atts, $atts );\r\n$title_styles = \"\";\r\n\/\/ generate color style\r\nif( ! empty( $params['title_color'] ) ) {\r\n$title_styles .= \"color: \" . $params['title_color'] . \";\";\r\n}\r\nreturn '&lt;div class=\"text-holder\"&gt;&lt;span class=\"text-title\" style=\"' . $title_styles . '\"&gt;' . esc_html( $params['title'] ) . '&lt;\/span&gt;&lt;\/div&gt;';\r\n}\r\nadd_shortcode( 'colored_text', 'custom_colored_text' );<\/pre>\n<p>[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Since we have explained the parameters of a handler function as well as how a shortcode can be registered in the previous sections, we will not go over it again here. Instead, we will focus on explaining the content of the handler function, one code block at a time. Each of the blocks concerns a different phase in the shortcode creation process, so we gave each appropriate names.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;22px&#8221;]<ul class=\"qodef-unordered-list-item qodef-toc\">\n    <li>\n\t        <div class=\"qodef-ul-title-holder\">\n            <span class=\"qodef-ul-title-content\"><strong>Extracting the attributes<\/strong><\/span>        <\/div>\n            <\/li>\n<\/ul>[vc_empty_space height=&#8221;28px&#8221;][vc_column_text]<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">$default_atts = array(\r\n\"title\" =&gt; '',\r\n\"title_color\" =&gt; ''\r\n);\r\n$params = shortcode_atts( $default_atts, $atts );<\/pre>\n<p>[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]The first thing you might notice is the $default_atts variable, which is an associative array. We have purposely named it <strong>$default_atts<\/strong>, to make it a bit clearer what it refers to. This variable <strong>contains all the default values of all the attributes used in the shortcode<\/strong>. Then, thanks to <a href=\"https:\/\/developer.wordpress.org\/reference\/functions\/shortcode_atts\/\" target=\"_blank\" rel=\"noopener noreferrer\">the shortcode_atts function<\/a> provided by the Shortcode API, <strong>the default values are compared with user-inserted values stored into the $atts variable. <\/strong>If a user omits using an attribute of a shortcode, it won\u2019t be stored inside the $atts variable. As the $default_atts array also serves as a list of all available shortcode attributes, <strong>a default value corresponding to the omitted shortcode attribute will be used instead<\/strong>. Furthermore, <strong>if a user accidentally inserts an invalid shortcode attribute, that attribute will be disregarded<\/strong> thanks to the same function.[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]With the intention of keeping this example simple, we have only included two possible attributes to this shortcode, both of which have empty strings as the default values. After cross-referencing the attributes and their values using the shortcode_atts function, the result is stored inside the <strong>$params<\/strong> variable, which is also an associative array.[\/vc_column_text][vc_empty_space height=&#8221;22px&#8221;]<ul class=\"qodef-unordered-list-item qodef-toc\">\n    <li>\n\t        <div class=\"qodef-ul-title-holder\">\n            <span class=\"qodef-ul-title-content\"><strong>Interacting with the attributes<\/strong><\/span>        <\/div>\n            <\/li>\n<\/ul>[vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Performing certain operations or interacting with the acquired attributes is the main part of creating a shortcode. Depending on the complexity of the shortcode, the length of this section of code can vary substantially. Even so, parts of this section can sometimes be divided into and written as separate semantically-structured functions, which can later be used within the handler function. But, as those are quite advanced and complex examples, we won\u2019t be dealing with them in this article.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Let us examine the code section used in our example.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Firstly, a reader can see that a new variable <strong>$title_styles<\/strong> is created and that it is set to an empty string. We will use the same variable within the if block placed below. As we mentioned before, the attributes and their corresponding values are placed within the $params associative array. You can access the corresponding value by using the <strong>$params[&#8216;atribute_name&#8217;]<\/strong> line of code.[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]The <a href=\"https:\/\/www.php.net\/manual\/en\/control-structures.if.php\" target=\"_blank\" rel=\"noopener noreferrer\">if block<\/a> simply states that if the user has added a title_color value, the corresponding CSS string rule will be added to the $title_styles variable. For example, if the title_color value was blue, the $title_styles variable would be equal to &#8220;color: blue;&#8221;.[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">$title_styles = \"\";\r\n\/\/ generate color style\r\nif( ! empty( $params['title_color'] ) ) {\r\n$title_styles .= \"color: \" . $params['title_color'] . \";\";\r\n}<\/pre>\n<p>[\/vc_column_text][vc_empty_space height=&#8221;22px&#8221;]<ul class=\"qodef-unordered-list-item qodef-toc\">\n    <li>\n\t        <div class=\"qodef-ul-title-holder\">\n            <span class=\"qodef-ul-title-content\"><strong>Returning the output<\/strong><\/span>        <\/div>\n            <\/li>\n<\/ul>[vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Finally, after interacting with the data and performing additional functions, it is time to return the shortcode output. Despite being bigger, the return statement used in this example doesn\u2019t differ greatly from the one used in the previous example, as it also features the string concatenation operator. Nevertheless, two things are different\u2014the mixed-use of double and single quotes as well as the use of an <a href=\"https:\/\/codex.wordpress.org\/Validating_Sanitizing_and_Escaping_User_Data\" target=\"_blank\" rel=\"noopener noreferrer\">escaping function<\/a> (<strong>esc_html<\/strong> in this example).[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]The return output string is denoted with single quotes. Therefore, if you need to use quotes within this string, you will need to use double-quotes. Since the mixed-use of single and double quotes can be quite confusing, we advise taking special care here as a misuse of quotes can break your site.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]As for the escaping function, it secures the output by removing any unwanted data and prevents cross-site scripting attacks.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">return '&lt;div class=\"text-holder\"&gt;&lt;span class=\"text-title\" style=\"' . $title_styles . '\"&gt;' . esc_html( $params['title'] ) . '&lt;\/span&gt;&lt;\/div&gt;';<\/pre>\n<p>[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Here\u2019s an example of how this shortcode would look inside a page sidebar.[\/vc_column_text][vc_empty_space height=&#8221;50px&#8221;]<div class=\"qodef-single-image-holder   qodef-has-border \">\n    <div class=\"qodef-si-inner\" >\n                                    <img loading=\"lazy\" decoding=\"async\" width=\"700\" height=\"374\" src=\"https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Text-Holder.jpg\" class=\"attachment-full size-full\" alt=\"Text Holder\" srcset=\"https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Text-Holder.jpg 700w, https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Text-Holder-300x160.jpg 300w, https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Text-Holder-620x331.jpg 620w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/>                        <\/div>\n<\/div>[vc_empty_space height=&#8221;72px&#8221;][vc_column_text]<\/p>\n<h3 class=\"qodef-h5\">Example 3:<\/h3>\n<p>[\/vc_column_text][vc_column_text]An even more complex task is <strong>creating an enclosing shortcode that accepts user attributes<\/strong>. Apart from the $atts variable, the shortcode also uses the $content variable. Additionally, you can assign a default value to the $content variable within the brackets that define the arguments of the handler function. In the example given below, <strong>the default value of the $content variable is set to null<\/strong>.[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Adding a custom button shortcode\r\nfunction custom_button_shortcode( $atts, $content = null ) {\r\n$default_atts = array(\r\n'text' =&gt; '',\r\n'link' =&gt; '#',\r\n'target' =&gt; '_self',\r\n'color' =&gt; '',\r\n'background_color' =&gt; '',\r\n'font_size' =&gt; '',\r\n'font_weight' =&gt; '',\r\n'padding' =&gt; '',\r\n'custom_class' =&gt; ''\r\n);\r\n$params = shortcode_atts( $default_atts, $atts );\r\n$button_styles = \"\";\r\n$button_classes = \"custom-btn\";\r\n\/\/ Creating the button styles\r\nif( ! empty( $params['color'] ) ){\r\n$button_styles .= 'color: '. $params['color'] .'; ';\r\n}\r\nif( ! empty( $params['background_color'] ) ){\r\n$button_styles .= 'background-color: '. $params['background_color'] .'; ';\r\n}\r\nif( ! empty( $params['font_size'] ) ){\r\n$button_styles .= 'font-size: '. $params['font_size'] .'; ';\r\n}\r\nif( ! empty( $params['font_weight'] ) ){\r\n$button_styles .= 'font-weight: '. $params['font_weight'] .'; ';\r\n}\r\nif( ! empty( $params['padding'] ) ){\r\n$button_styles .= 'padding: '. $params['padding'] .'; ';\r\n}\r\n\/\/ Adding the custom class\r\nif ( ! empty( $params['custom_class'] ) ){\r\n$button_classes .= $params['custom_class'];\r\n}\r\nreturn '&lt;div&gt;&lt;p&gt;' . esc_html( $content ) . '&lt;\/p&gt;&lt;a itemprop=\"url\" href=\"' . esc_url( $params['link'] ) . '\" target=\"' . esc_attr( $params['target'] ) . '\"' . ' style=\"' . $button_styles . '\" ' . 'class=\"' . $button_classes . '\" &gt;' . esc_html( $params['text'] ) . '&lt;\/a&gt;&lt;\/div&gt;';\r\n}\r\nadd_shortcode( 'custom_button', 'custom_button_shortcode' );<\/pre>\n<p>[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]By comparing the codes from examples 2 and 3, you can see the same structural pattern emerging. Apart from the amount of code, the sections differ very little. Therefore, we will not go into detail regarding each of the three sections once more, instead we will only highlight the most important things.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]The same warnings mentioned towards the end of the second example still hold. Meaning, you should take special care when mixing single and double-quotes. Also, try to escape the variables you use in your output as much as possible, for security reasons. We did this in the third example by using esc_html, esc_url, and esc_attr functions. Additionally, as this is an enclosing type shortcode, including the $content variable within the output string is mandatory. We also suggest including a custom class as one of your shortcode attributes. This will allow users to further alter the shortcode by creating custom CSS or JS code snippets to target that custom class.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Here\u2019s an example of how the same shortcode would look placed in a widget inside of a website footer.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;50px&#8221;]<div class=\"qodef-single-image-holder   qodef-has-border \">\n    <div class=\"qodef-si-inner\" >\n                                    <img loading=\"lazy\" decoding=\"async\" width=\"700\" height=\"374\" src=\"https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Text-Widget-Inspect.jpg\" class=\"attachment-full size-full\" alt=\"Text Widget Inspect\" srcset=\"https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Text-Widget-Inspect.jpg 700w, https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Text-Widget-Inspect-300x160.jpg 300w, https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Text-Widget-Inspect-620x331.jpg 620w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/>                        <\/div>\n<\/div>[vc_empty_space height=&#8221;68px&#8221;][\/vc_column][\/vc_row][vc_row][vc_column][vc_column_text]<\/p>\n<h2 class=\"qodef-h4\"><a id=\"using-custom-shortcodes\"><\/a>Using custom shortcodes<\/h2>\n<p>[\/vc_column_text][vc_column_text]You can use custom shortcodes in various parts of your website. The easiest way of using your shortcode is by inserting it in one of the widget areas\/sidebars. To do so, you only need to add the appropriate shortcode \u201ccall\u201d inside a text widget, placed in a widget area of your choice.[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]In terms of the steps you need to take, first <strong>navigate to Appearance &gt; Widgets<\/strong>. Then <strong>find the Text widget<\/strong> from the list of Available Widgets on the left side of your screen. <strong>Click on the Text widget, select the widget area<\/strong> where you want to add this widget, and <strong>press the Add Widget button<\/strong>. Another way of performing the same task is simply by dragging and dropping the Text widget inside the whichever widget area you want.[\/vc_column_text][vc_empty_space height=&#8221;50px&#8221;]<div class=\"qodef-single-image-holder   qodef-has-border \">\n    <div class=\"qodef-si-inner\" >\n                                    <img loading=\"lazy\" decoding=\"async\" width=\"700\" height=\"374\" src=\"https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Appearance-Widgets.jpg\" class=\"attachment-full size-full\" alt=\"Appearance Widgets\" srcset=\"https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Appearance-Widgets.jpg 700w, https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Appearance-Widgets-300x160.jpg 300w, https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Appearance-Widgets-620x331.jpg 620w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/>                        <\/div>\n<\/div>[vc_empty_space height=&#8221;38px&#8221;][vc_column_text]After inserting the Text widget, <strong>click on it to open, and add the appropriate code<\/strong>. Afterward, <strong>press the Save button<\/strong> and <strong>check the shortcode<\/strong> visual output on your website\u2019s frontend.[\/vc_column_text][vc_empty_space height=&#8221;50px&#8221;]<div class=\"qodef-single-image-holder   qodef-has-border \">\n    <div class=\"qodef-si-inner\" >\n                                    <img loading=\"lazy\" decoding=\"async\" width=\"700\" height=\"374\" src=\"https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Text-Shortcode.jpg\" class=\"attachment-full size-full\" alt=\"Text Shortcode\" srcset=\"https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Text-Shortcode.jpg 700w, https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Text-Shortcode-300x160.jpg 300w, https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Text-Shortcode-620x331.jpg 620w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/>                        <\/div>\n<\/div>[vc_empty_space height=&#8221;38px&#8221;][vc_column_text]In the screenshot above, you can see the code for using the custom button we created in our third example.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">[custom_button text = 'More here' link = 'some-url-here' target = '_blank' color = 'black' background_color = 'white' font_size = '14px' font_weight = 'bold' padding = '15px 25px'] Stay motivated and succeed [\/custom_button]<\/pre>\n<p>[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Since that represents an enclosing shortcode with parameters, it can be the hardest one to use. Thus, let us break down its use carefully.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Firstly, to use it, you have to insert the appropriate opening and closing shortcode tags. Those are [custom_button] and [\/custom_button], respectively. Between those two tags, you can see the user-inserted content. That is the <strong>Stay motivated and succeed<\/strong> line. Finally, the opening shortcode tag contains the attributes, alongside their corresponding values. They are given as <strong>attribute_name<\/strong> = <strong>&#8216;attribute_value&#8217;<\/strong> pairs.[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Apart from including the shortcodes inside widgets, you can add them directly to your pages. The required steps depend solely on the page builder plugin you are using. We will mention a few below.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;22px&#8221;]<ul class=\"qodef-unordered-list-item qodef-toc\">\n    <li>\n\t        <div class=\"qodef-ul-title-holder\">\n            <span class=\"qodef-ul-title-content\"><strong>WPBakery<\/strong><\/span>        <\/div>\n            <\/li>\n<\/ul>[vc_empty_space height=&#8221;28px&#8221;][vc_column_text]To use your shortcode in WPBakery, <strong>add a Text Block element<\/strong> to your page and <strong>paste the code in the Visual section of the General tab<\/strong>. <strong>Click the Save changes button<\/strong> and <strong>update the page<\/strong> afterward. Make sure to check the visual output on the frontend as well.[\/vc_column_text][vc_empty_space height=&#8221;50px&#8221;]<div class=\"qodef-single-image-holder   qodef-has-border \">\n    <div class=\"qodef-si-inner\" >\n                                    <img loading=\"lazy\" decoding=\"async\" width=\"700\" height=\"351\" src=\"https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/WPBakery-Shortcode.jpg\" class=\"attachment-full size-full\" alt=\"WPBakery Shortcode\" srcset=\"https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/WPBakery-Shortcode.jpg 700w, https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/WPBakery-Shortcode-300x150.jpg 300w, https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/WPBakery-Shortcode-620x311.jpg 620w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/>                        <\/div>\n<\/div>[vc_empty_space height=&#8221;50px&#8221;]<ul class=\"qodef-unordered-list-item qodef-toc\">\n    <li>\n\t        <div class=\"qodef-ul-title-holder\">\n            <span class=\"qodef-ul-title-content\"><strong>Elementor<\/strong><\/span>        <\/div>\n            <\/li>\n<\/ul>[vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Similarly, you can use the same shortcode within Elementor by <strong>adding the Text Editor widget<\/strong>, inside your page. <strong>Insert the code in the Visual section<\/strong> and <strong>update the page<\/strong> afterward. Make sure to check the visual output on the frontend as well.[\/vc_column_text][vc_empty_space height=&#8221;50px&#8221;]<div class=\"qodef-single-image-holder   qodef-has-border \">\n    <div class=\"qodef-si-inner\" >\n                                    <img loading=\"lazy\" decoding=\"async\" width=\"700\" height=\"438\" src=\"https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Elementor-Shortcode.jpg\" class=\"attachment-full size-full\" alt=\"Elementor Shortcode\" srcset=\"https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Elementor-Shortcode.jpg 700w, https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Elementor-Shortcode-300x188.jpg 300w, https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Elementor-Shortcode-620x388.jpg 620w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/>                        <\/div>\n<\/div>[vc_empty_space height=&#8221;50px&#8221;]<ul class=\"qodef-unordered-list-item qodef-toc\">\n    <li>\n\t        <div class=\"qodef-ul-title-holder\">\n            <span class=\"qodef-ul-title-content\"><strong>Gutenberg<\/strong><\/span>        <\/div>\n            <\/li>\n<\/ul>[vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Using your newly created shortcode isn\u2019t much different in Guttenberg, compared to the other page builders. <strong>Click on the + sign<\/strong> to add a new block and <strong>search for the term Shortcode<\/strong>. <strong>Add the Shortcode block<\/strong> to your page and <strong>insert the code within it<\/strong>. Then, update the page. Make sure to check the visual output on the frontend as well.[\/vc_column_text][vc_empty_space height=&#8221;50px&#8221;]<div class=\"qodef-single-image-holder   qodef-has-border \">\n    <div class=\"qodef-si-inner\" >\n                                    <img loading=\"lazy\" decoding=\"async\" width=\"700\" height=\"374\" src=\"https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Gutenberg-Shortcode.jpg\" class=\"attachment-full size-full\" alt=\"Gutenberg Shortcode\" srcset=\"https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Gutenberg-Shortcode.jpg 700w, https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Gutenberg-Shortcode-300x160.jpg 300w, https:\/\/qodeinteractive.com\/magazine\/wp-content\/uploads\/2020\/08\/Gutenberg-Shortcode-620x331.jpg 620w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/>                        <\/div>\n<\/div>[vc_empty_space height=&#8221;38px&#8221;][vc_column_text]The code we inserted into all three page builders came from our second shortcode example.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">[colored_text title='About us' title_color = '#d77a61']<\/pre>\n<p>[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Since it is a self-closing shortcode, it only has an opening shortcode tag with the appropriate shortcode name (colored_text). Additionally, the attributes and their corresponding values are inserted within that tag as attribute_name = &#8216;attribute_value&#8217; pairs.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Finally, you can use your custom shortcodes within your theme template files using the <a href=\"https:\/\/developer.wordpress.org\/reference\/functions\/do_shortcode\/\" target=\"_blank\" rel=\"noopener noreferrer\">do_shortcode<\/a> function. If you choose to do that, you will have to use a line of code in your header.php, footer.php, or any other theme template file that would be similar to this one:[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?php echo do_shortcode(\"[shortcode_name]\"); ?&gt;<\/pre>\n<p>[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]However, this practice has fallen out of favor recently, so we suggest that you restrict the use of the do_shortcode function within a custom-made plugin.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;68px&#8221;][\/vc_column][\/vc_row][vc_row][vc_column][vc_column_text]<\/p>\n<h2 class=\"qodef-h4\"><a id=\"additional-tips\"><\/a>Additional tips<\/h2>\n<p>[\/vc_column_text][vc_column_text]Now that you\u2019ve seen how the process of creating a shortcode goes in detail, we can share some additional tips and common practices. Even though these are mostly intended for developers, examining this section can prove useful for any reader interested in building custom shortcodes.<br \/>\n[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Firstly, we don\u2019t advise adding code to your <strong>template files<\/strong> as those changes will get overridden by theme updates. On the same note, we also discourage creating the shortcode within the <a href=\"https:\/\/qodeinteractive.com\/magazine\/wordpress-functions-php-tricks\/\">functions.php file<\/a>. The reason being is that every time you decide to deactivate that theme, the shortcodes created within the <strong>functions.php<\/strong> file will stop working. At the same time, shortcode \u201ccalls\u201d are part of your content, and as such are stored in your database. This means your site will contain unrendered shortcodes that will be visible to your users and could confuse or scare them. Therefore, it is best to create a custom plugin and include your shortcode within it.[\/vc_column_text][vc_empty_space height=&#8221;28px&#8221;][vc_column_text]Additionally, shortcodes will often require you to write custom CSS or JS code that helps with the stylization or provides additional features. It would be best to create separate CSS and JS stylesheet files and enqueue them within the plugin you created <a href=\"https:\/\/qodeinteractive.com\/magazine\/how-to-enque-scripts-wordpress\/\">using the wp_enqueue_style and wp_enqueue_script functions<\/a>. Furthermore, we suggest splitting the code into separate functions, if possible. And for easier organization, you should also try to create a distinct structure of files and folders within the directory of your plugin. This structure should correspond to distinct code sections found within your shortcode. Finally, you should try to follow some of the <a href=\"https:\/\/www.freecodecamp.org\/news\/css-naming-conventions-that-will-save-you-hours-of-debugging-35cea737d849\/\" target=\"_blank\" rel=\"noopener noreferrer\">latest naming conventions for the CSS classes<\/a> included in your output HTML. This will let you write the additional CSS and JS code easily and it will improve the readability of your code as a whole.[\/vc_column_text][vc_empty_space height=&#8221;68px&#8221;][\/vc_column][\/vc_row][vc_row][vc_column][vc_column_text]<\/p>\n<h2 class=\"qodef-h4\">Final Thoughts<\/h2>\n<p>[\/vc_column_text][vc_column_text]You can use shortcodes for a wide array of reasons and all across your website. If you are using a theme or plugin that is missing some features you might find useful, then creating shortcodes can supplement that. Shortcodes can add a missing or previously unavailable feature to your website and even improve its functionality substantially. As this is quite an extensive topic, we have tried to cover it in as much detail as possible in this article. We supplied you with examples of increasing difficulty in an effort to cover all the possible steps of the shortcode creation process and provide you with resources to build on. Using these examples, we are confident you will be able to create shortcodes of your own and improve them even further.<br \/>\n[\/vc_column_text][\/vc_column][\/vc_row]<\/p>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Shortcodes are the bread and butter of page builders. Find out how to create a shortcode in WordPress and augment your page building efforts.<\/p>\n","protected":false},"author":11229,"featured_media":11238,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[14,21,4,13],"class_list":["post-11191","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tutorials","tag-core","tag-php","tag-tips","tag-wordpress"],"_links":{"self":[{"href":"https:\/\/qodeinteractive.com\/magazine\/wp-json\/wp\/v2\/posts\/11191","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/qodeinteractive.com\/magazine\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/qodeinteractive.com\/magazine\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/qodeinteractive.com\/magazine\/wp-json\/wp\/v2\/users\/11229"}],"replies":[{"embeddable":true,"href":"https:\/\/qodeinteractive.com\/magazine\/wp-json\/wp\/v2\/comments?post=11191"}],"version-history":[{"count":0,"href":"https:\/\/qodeinteractive.com\/magazine\/wp-json\/wp\/v2\/posts\/11191\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/qodeinteractive.com\/magazine\/wp-json\/wp\/v2\/media\/11238"}],"wp:attachment":[{"href":"https:\/\/qodeinteractive.com\/magazine\/wp-json\/wp\/v2\/media?parent=11191"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/qodeinteractive.com\/magazine\/wp-json\/wp\/v2\/categories?post=11191"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/qodeinteractive.com\/magazine\/wp-json\/wp\/v2\/tags?post=11191"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}