Understanding and using WordPress Shortcodes

• 5 minutes READ

WordPress as a platform provides really good support for plugin developers to create functionality on top of WordPress. WordPress lets the plugin developer create functionality which the post creator can use as a macro in the post or the page he publishes. These macros are called as Shortcode.

The WordPress platform provides a very good API support for creating shortcodes. WordPress shortcode api’s provide good support for creating shortcodes, removing shortcodes , parsing the arguments of shortcode etc . This makes the plugin developer just concentrate on the functionality he wants to provide via his shortcode and not worry about the other infrastructure things required for the shortcode.

In this article we are going to see what all support does WordPress provide to create a shortcode and how to use WordPress shortcode api’s and create your own shortcodes.

Creating a simple Shortcode

Let’s start by creating a simple shortcode which displays the latest five posts with their titles and links to them. The code to create the shortcode is as follows:

function display_latest_post()
{

    $result = '';
    $query = new WP_Query( 'posts_per_page=3' );
    // The Loop
    while ( $query->have_posts() ) : $query->the_post();
        $result.= '<li>';
        $result.= '<a href="'.get_permalink().'">'.get_the_title().'</a>';
        $result.= '</li>';
    endwhile;

    // Reset Post Data
    wp_reset_postdata();

    //return the result
    return $result;
}

function register_shortcodes(){
  add_shortcode( 'DISPLAY_LATEST_POSTS', 'display_latest_post' );
}

add_action( 'init', 'register_shortcodes');

In the above code we first create a function display_latest_post. This function uses WP_Query to query the WordPress post to get the latest three posts from the database. Then we loop on the query to get the post title and the permalink of the post. Then we return the result from the function.

Once we have written the function for getting the latest post to create a shortcode to display the latest post we will have to use the add_shortcode function provided by WordPress. The add_shortcode function takes two arguments, first the tag which will be used in the post content and second is the name of the function. Hence we use the add_shortcode function as

No-Code Email Template Builder

With Postcards Email Builder you can create and edit email templates online without any coding skills! Includes more than 100 components to help you create custom emails templates faster than ever before.

Free Email BuilderFree Email Templates
add_shortcode( 'DISPLAY_LATEST_POSTS', 'display_latest_post' );

For more details on add_shortcode you can visit the following link.

Once we have added the above code our shortcode is ready for use.To use our shortcode we create a new post and add the shortcode tag in square brackets as shown below:

WordPress Shortcodes Image 1

Once we create the post and go to the post page we will see the latest three posts on it with its permalink as follows:

WordPress Shortcodes Image 2

Passing arguments to shortcode

The above shortcode is a basic shortcode and does not take any arguments and cannot be customized when adding in the post content. WordPress also provides a way to add arguments to the shortcode which can be used to customize the output of the shortcode. This really can enhance the value of a particular shortcode.

Now let’s modify the above Shortcode to take arguments like number of post to display and to display post from some specific category.

The code will be as follows:

Low-Code Website Builders

With Startup App and Slides App you can build unlimited websites using the online website editor which includes ready-made designed and coded elements, templates and themes.

Try Startup App Try Slides AppOther Products
function display_latest_post($atts)
{
    extract( shortcode_atts( array(
		'numberofpost' => '3',
		'categoryid' => '',
	), $atts ) );

    $result = '';
    $querystring = 'posts_per_page='.$numberofpost;
    if(strlen($categoryid) > 0)
        $querystring .= '&cat='.$categoryid;
    $query = new WP_Query( $querystring );
    // The Loop
    while ( $query->have_posts() ) : $query->the_post();
        $result.= '<li>';
        $result.= '<a href="'.get_permalink().'">'.get_the_title().'</a>';
        $result.= '</li>';
    endwhile;

    // Reset Post Data
    wp_reset_postdata();

    //return the result
    return $result;
}

Here now in function display_latest_post we take the arguments which can be passed from the shortcode. Then we pass the arguments which we get from the shortcode and a array of default values to the WordPress function shortcode_atts. The function shortcode_atts merges the two values from the default array and from the array which is passed as argument. This becomes useful as in some cases the person using the shortcode might not want to specify all the arguments and might just want to pass some arguments.

You can get more details about shortcode_atts at the following link.

Then in case the arguments are passed to our shortcode function we will use those values and create the query for WP_Query appropriately.

So in case if I want to show only one post in category 10, I will use the shortcode as follows:

WordPress Shortcodes Image 3

The output on the post will be as follows:

WordPress Shortcodes Image 4

Using enclosing Shortcodes

WordPress allows to even us enclose only some part of the content of the post between the shortcode. Then that content is passed to your shortcode handler and then based on the content or some other logic the shortcode handler can return the appropriate content back.

Now let’s create a small enclosing shortcode which will show the content itself if the user is logged in and will hide the content and show the login link in case the user viewing the post is not logged in.

The code for our shortcode is as follows:

function check_logged_in( $atts, $content = null )
{
    if ( is_user_logged_in() )
      return  $content;
    else
     return '<a href="'.wp_login_url().'" title="Login">Please login to see the content</a>';
}

function register_shortcodes(){
  add_shortcode( 'DISPLAY_LATEST_POSTS', 'display_latest_post' );
  add_shortcode( 'CHECK_LOGGED_IN', 'check_logged_in' );
}

In our shortcode handler the second argument passed is the content which will be enclosed by our shortcode. In our handler we first check if the user has logged in using the WordPress function is_user_logged_in(). In case he has not then we get the login url from the WordPress function wp_login_url and then return a link to the login page.

The ‘CHECK_LOGGED_IN’ shortcode can be used on partial content of a post as shown below:

WordPress Shortcodes Image 5

In case the user is logged in the output will be as follows:

WordPress Shortcodes Image 6

In case the user is not logged in the content of the post will be as follows:

WordPress Shortcodes Image 7

Apply Shortcodes Programmatically

Till now we saw how to create shortcodes using the WordPress shortcode API. We also saw how we can use the shortcodes in our post or pages content.

We can even use the shortcode in our templates or as part of some other function in our theme or plugin. This can be done with the help of the WordPress function do_shortcode.

The WordPress function do_shortcode takes in the content and in case there are any shortcodes inside that content those will be evaluated and returned as the output of the function.

So in case we want to display the latest post in our theme we can do it using our shortcode as follows:

echo do_shortcode('[DISPLAY_LATEST_POSTS]');

Some other useful WordPress Shortcode functions

Once we are comfortable with creating and using WordPress shortcodes now let’s take a look at some other helpful functions which WordPress provides related to shortcodes.

  • remove_shortcode –

This function takes in the tag used to add the shortcode. This function removes a shortcode which was previously added with add_shortcode. This might be useful in case you have multiple plugins adding shortcodes and you don’t want some of the shortcodes to be used on your site.

  • remove_all_shortcodes –

This function removes all the added shortcode.

  • strip_shortcodes –

This function takes in the content as a parameter and strips off all the shortcode tags in the content. This function might be useful in case you want to show the shortcodes only on some particular pages.

Conclusion

WordPress as a platform provides a great level of api support to create shortcodes. Shortcodes in WordPress are easy to create and are easy to use. Very useful functionality of various kinds can be provided using WordPress shortcode. So have fun while using shortcode in the next WordPress plugin you use.

Abbas Suterwala

I am Abbas Suterwala, a software engineer by profession and a passionate coder. I live every moment at the fullest. I love open source projects and mobile development, and I am especially interested in WordPress as blogging platform.

Posts by Abbas Suterwala
🍪

We use cookies to ensure that we give you the best experience on our website. Privacy Statement.

  • I disagree
  • I agree