WordPress Shortcodes Basics

WordPress Shortcodes Basics

In WordPress, there is a toolset feature called shortcode. Shortcodes are one of the powerful engines of WordPress that makes it extremely customizable and flexible, allowing you to execute code within a post or page contents, text widgets, and at various endpoints

In this tutorial, I will cover a brief introduction to WordPress shortcodes and their benefits. I will also show you what a shortcode consists of.

Shortcodes were introduced in version 1.0. In WordPress, a shortcode is a minified tag representing a piece of code. The tag makes it easy for you to effortlessly utilize created shortcodes at various endpoints.

Shortcodes allow you to add a piece of code to a WordPress post or page content area, or within text widgets. WordPress then will execute this piece of code whenever the post or page content is viewed on screen, or whenever the text widget is displayed.

The format (minified tag representation) of shortcode is as follow: [shortcode_tag]

By default, WordPress comes with a handful of prebuilt-shortcodes. For example, the

shortcode is used to embed a video within your site, the [image] shortcode is used to display a particular image and the shortcode allows you to wrap captions around content.

Let’s take a look at the three important benefits of shortcodes.


Benefit #1.  Shortcodes simplify content and layout creation

With shortcodes, you don’t repeat yourself everytime you want to do something that occurs repeatedly, or write posts that have similar content formatting. For example, if you want to quote one author or more on a post, instead of re-writing the quote markup every time, shortcode allows you to write the quote markup just once and re-use it whenever it is needed.

Same for drafting out a particular page layout. Imagine that you want your users to be able to select a particular page for login, registration, and custom dashboard. With shortcodes, this comes handy. All they have to do is to create the page from the editing screen and insert the custom shortcode you’ve created for each page layout. For example, a login page will use the [login_page] shortcode, a registration page will use the [register_page] shortcode, and a custom dashboard page will use the [custom_dashboard] shortcode.


Benefit #2. Shortcodes improve your efficiency and productivity

Shortcodes tremendously improve efficiency, enabling you to perform a complex task instantly. Shortcodes give you more valuable time to work effectively and be organized. They also increase productivity because you are able to achieve the same functionality on a post or page creation with little code and time.


Benefit #3. Shortcodes provide access to an unreachable content area

Shortcodes enable you to gain access to content areas that are not easy to access. For instance, with the help of shortcode, you can easily build your own custom widgets sidebar.

The use of shortcodes opens up endless possibilities to control and customize the entire site functionality at various endpoints.

In order for you to grasp how shortcodes work and how they get created, we are going to explore its components,


Components of a Shortcode

I have divided shortcodes into the following five components:

  1. Types of shortcodes
  2. Shortcode callback() function
  3. The add_shortcode() function
  4. Shortcode attributes
  5. Utilizing shortcodes

Types of shortcodes

There are two types of WordPress shortcodes:

  1. Self-closing shortcodes
  2. Enclosing shortcodes.

1. Self-Closing Shortcodes

This type of shortcode is similar to HTML tags such as: <br>, <hr>, <meta> etc. They don’t require a closing tag, they are already enclosed in their default format: [shortcode_tag]. If you still want to close it, then you need to add a forward slash (/) before the (]) character: [shortcode_tag /]. Take note of the space before the forward slash.


2. Enclosing Shortcodes

Unlike self-closing shortcode, the enclosing shortcode format is a little bit different. When using this type of shortcode, the tag must be written explicitly otherwise the expected behavior will be broken. This shortcode is similar to html tags such as: <div>content</div>, <p>content</p>, <span>content</span> etc. The format for this shortcode is as follow: [shortcode_tag]content[/shortcode_tag].


Shortcode callback function

This is a custom PHP function that is used to implement your shortcode functionality. This function is expected to ‘return’ whatever data or content it has created for usage because in most cases when a shortcode callback function outputs any data directly, the data may appear in a weird position on your site. A PHP function looks like this: <?php function my_function_name() { // code } ?>


The add_shortcode() function

This function is used to register a shortcode handler which will create the given shortcode tag. In short, the add_shortcode() function tells WordPress to treat the ‘callback_function’ as a shortcode. It has two parameters: $shortcode_tag and $callback_function


Usage

<?php add_shortcode( $shortcode_tag, $callback_function ); ?>

Parameters explained

  • $shortcode_tag: (string) This parameter is required. It specifies the shortcode tag to bind the custom callback function with, which will be searched for in post content. It must never contain the following characters: (Square braces: [ ]), (Angle braces : < >), (Ampersand: &), (Forward slash: ⁄), (Whitespace: space linefeed tab), (Non-printing characters: \x00 – \x20). Also, it is highly recommended to avoid the use of quotes in shortcode tags: (Quotes: ” ‘).
  • $callback_function: (callable) This parameter is required. It specifies the custom handler (callback function) to execute whenever the shortcode tag is found. Note: The add_shortcode() function will pass three arguments ($atts, $content, $tag) to the custom shortcode handler (callback function). The arguments description is as follows: $atts: An associative array of attribute, or an empty string if no attributes are given. $content: The enclosed content (only when the shortcode is used in its enclosing form), or an empty string if the shortcode is used in its self-closing form. $tag:The shortcode tag (name of the shortcode). Very useful for shared callback functions.

Shortcode attributes

WordPress shortcodes support attributes (parameters) just like normal html tags. For example, this html tag and attributes <p id=”p-id” class=”p-class”> can be re-written in shortcode as follow: [shortcode_tag id=”p-id” class=”p-class”]. However in the case of shortcode, for attributes to work correctly, you must create support for it by using a Shortcode API called shortcode_atts().


The shortcode_atts() function

This function combines user shortcode attributes with default options. It uses the user shortcode attributes if they are set to override the default options, otherwise, the default options are used. So the result from this function will contain every key from the default options, merged with values from the shortcode attributes. Also, this function will ignore and remove all user shortcode attributes that are not present (supported) in the list of default shortcode attributes.


Usage

<?php shortcode_atts($pairs, $atts, $shortcode_tag); ?>

Parameters Explained

$pairs: (array) A required parameter. Specifies the entire list of supported attributes and their default values. This is viewed as the shortcode default options.

$atts: (array) A required parameter. Specifies the user-defined attributes in shortcode tag. This is used to override the default options.

$shortcode_tag: (string) An optional parameter. The shortcode name to be used by the shortcode_atts_{shortcode} filter. If this is present, it makes a ‘shortcode_atts_$shortcode’ filter available for other code to filter attributes. This parameter should always be included for maximum compatibility, albeit, it is an optional variable.

This function returns an array consisting of the combined and filtered attribute list.

Note: Shortcode attribute names are always converted to lowercase before they are passed into the shortcode callback function. For instance, [shortcode_tag USERNAME="OSTraining"] produces $atts = array('username' => "OSTraining");


An overview of shortcode attributes

  • The shortcode parser does not accept square brackets within attributes. Here’s an example that will not be parsed: [shortcode_tag attribute=”[value]”].
  • Shortcode macros may use single or double quotes for attribute values, or omit them entirely if the attribute value does not contain spaces. So this shortcode: [shortcode_tag attr1="value1" attr2='value2' attr3=123] is equivalent to [shortcode_tag attr1="value1" attr2="value2" attr3="123"].
  • Starting with version 3.9.3, use of HTML is limited inside shortcode attributes. Thus the following shortcode example will not work correctly because it contains a ‘<‘ character: [shortcode_tag attr1="value1" attr2="value2" compare="<"]. However if you need to use the ‘<‘ and ‘>’ characters, consider using their corresponding HTML entity.
  • Starting with version 4.0 only validated HTML is allowed in attribute values, so the following will work: [shortcode_tag title="<h2>OSTraining</h2>"].
  • Attributes values must never contain the following characters: ( Square braces: [] ), ( Quotes: ” ‘ ). However double quotes are allowed inside of single-quoted values and vice versa, but this is not recommended when dealing with user input. Also, the following characters must be escaped within attribute values, otherwise they will be stripped automatically and converted to spaces: (No-break space: \xC2\xA0 ), (Zero-width space: \xE22\x80\x8B )
  • Attribute names are optional and should contain only the following characters for maximum compatibility across all platforms: ( Upper-case and lower-case letters: A-Z a-z ), ( Digits: 0-9 ), ( Underscore: _ ), ( Hyphen: – ).

Important: Using hyphens in supported versions (4.3.0 and higher) can have implications that you may not be aware of, such as if other registered shortcodes also are using hyphens, the use of generic words with hyphen may cause collisions (if shortcodes are together within the same request).


Utilizing Shortcodes

After creating your custom shortcode, the next thing is to determine how to use it correctly. There are two ways to make use of your custom shortcode:

  • Adding it directly to the body area in the text editor.
  • Calling it directly within your plugin php script by using the do_shortcode() function.
    <?php echo do_shortcode( "[shortcode_tag]" ); ?>

Note that you could also use the apply_filters() function to filter shortcode within a given content.

<?php $my_shortcode = do_shortcode( '[shortcode]' );  echo apply_filters( 'the_content', $my_shortcode ); ?>

The do_shortcode() function

This function searches content for shortcodes and filters shortcodes through their hooks. The content of the shortcode will be returned without filtering if there are no shortcode tags found. Furthermore, this function can also be used to call a shortcode within your PHP file by passing the shortcode tag wrapped inside square brackets. This function has two parameters: $content and $ignore_html.


Usage


When searching content for shortcodes:
<?php do_shortcode( $content, $ignore_html ); ?>

When calling a self-closing shortcode:

<?php echo do_shortcode( '[shortcode_tag]' ); ?>

Calling a self-closing shortcode with attributes:
<?php echo do_shortcode( '[shortcode_tag attr1="value1" attr2="value2"]' ); ?>

When calling an enclosing shortcode:
<?php echo do_shortcode( '[shortcode_tag]' . $content_here . '[/shortcode_tag]' ); ?>

Calling an enclosing shortcode with attributes:
<?php echo do_shortcode( '[shortcode_tag attr1="value1" attr2="value2"]' . $content_here . '[/shortcode_tag]' ); ?>

Ignore shortcodes that are inside HTML elements:
<?php echo do_shortcode( '[shortcode_tag]', true ); ?>

Parameters explained

$content: (string) This is a required parameter. It specifies the content to search for shortcodes. $ignore_html: This is a boolean parameter and it is optional. It specifies whether the shortcode parser should parse or ignore shortcodes inside HTML elements. If true, shortcodes inside HTML elements will be ignored, false will filter shortcodes inside HTML elements. The default is: false. Note that you can also store the shortcode in a variable like so: <?php $shortcode_var = do_shortcode( ‘[shortcode_tag]’ ); ?>

Having everything in place, before we demonstrate our first shortcode example I would like us to have an idea about where to save our custom shortcodes.

A PHP file used to write the code to achieve your custom shortcodes functionality is extremely important. Although you could save your custom shortcodes in your current theme’s funcitons.php file, that is not recommended. Whenever you update the theme, all your editing in the functions.php file will be erased. Also, switching to a new theme means you must copy the custom shortcodes from the previous theme functions.php file into the newly activated theme functions.php file.

The recommended way to efficiently code your custom shortcode functionality is to create your own custom plugin in the plugin folder and insert your code into the plugin file.

Author

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x