Home » Source Book » How to Add Shortcode in WordPress

How to Add Shortcode in WordPress

Last updated on May 30, 2020 by

Table of Contents
1. What is Shortcode in WordPress
2. Points that You have to Keep in Mind While Adding Shortcode (Recommended)
3. Add Simple Shortcode in WordPress
4. add_shortcode() With Parameters
5. Code Explanation

As the name suggests add_shortcode() function is used to add/register the shortcode in WordPress. It accepts two parameters. The first parameter is the name of the shortcode and the second parameter is a callback function’s name. Both parameters are required.

Syntax: add_shortcode( 'name_of_shortcode', 'callback_function_name' );

A Simple Real Life Example of add_shortcode():

function dynamic_copyright_year(){
    return date('Y'); // Return current year
}

add_shortcode('copyright_year', 'dynamic_copyright_year');

What is Shortcode in WordPress

Shortcode is a short name of your bunch of a function’s code which allows you to execute anywhere in WordPress by just calling that short name.

  1. A shortcode name should be in lowercase and use all letters. The numbers or underscores will works fine too
  2. Do not use any spaces or reserved characters (& / < > [ ] = ‘ ” Whitespace) in the name of shortcode
  3. The name of the shortcode should be unique because if another plugin has a similar shortcode then it will override yours and yours will override theirs depending on which order the plugins are included and/or ran.
  4. Always use return for the output and not echo – anything. It will generate unexpected output if you echoed anything.
  5. The shortcode callback function will accept three arguments (parameters). All the arguments are optional. They are: the shortcode attributes, the shortcode content (if any), and the name of the shortcode itself, in that order.

Let’s now create a shortcode in WordPress with very simplest example.

Add Simple Shortcode in WordPress

We presume that you have read all the above points and content so now let’s add simple shortcode which will print the modified date of the current post or page. For that, we can get the modified date by using WordPress’s in-built get_the_modified_date() function.

/*@ Modified date shortcode */
if (!function_exists('sc_post_modified_date')) :

	function sc_post_modified_date() {
	    return get_the_modified_date();
	}
	add_shortcode( 'sc_modified_date', 'post_modified_date' );

endif;

In the above example, We have created a simple function(sc_post_modified_date) and return the modified date then we have used add_shortcode() function to register our shortcode. We have also passed the shortcode name (sc_modified_date) and callback function name (sc_post_modified_date). Thus our simplest shortcode is ready to use.

To execute this shortcode, place shortcode name inside two square brackets like [sc_post_modified_date] and add this shortcode to any post or page’s editor. If you are using a traditional/classic editor then you can directly add into it, but if you are using Gutenberg then there is a shortcode block available.

You can also use shortcodes with any WordPress hook’s. If you want to print shortcode via programming then you can use echo do_shortcode("[sc_post_modified_date]");

add_shortcode() With Parameters

To understand add_shortcode() with parameters, we will see a simple example of a recent posts shortcode. Here, we will get recent posts based on the category id. This recent post shortcode will accept 4 parameters (category id, number of posts, order, order by) but from them, only one will be required while others will be optional. Let’s just create the shortcode.

/*
 * Example of shortcode with attributes
 */

function sc_get_recent_posts( $atts ) {
    
    global $post;

    extract(shortcode_atts(array(
        'category_id'     => '',
        'number_of_posts'     => '5',
        'order'   => 'DESC',
        'orderby' => 'post_date',
    ), $atts));
    
    $args = array(
        'category'       => $category_id,
        'numberposts'    => $number_of_posts,
        'order'          => $order,
        'orderby'        => $orderby,
    );
    
    $output = '';
    
    $posts = get_posts($args);
    
    if ( !empty( $posts ) ) :

        foreach ( $posts as $post ) :
            
            setup_postdata($post);
 
            $output .= '<li><a href="'. get_the_permalink() .'">'. get_the_title() .'</a></li>';
            
        endforeach;

    else:

        $output .= '<li>No posts found</li>';

    endif;
    
    wp_reset_postdata();
    
    return '<ul>'. $output .'</ul>';
    
}

add_shortcode('sc_recent_posts', 'sc_get_recent_posts');

To execute the above-created shortcode add the [sc_recent_posts category_id="31" number_of_posts="5"] into your posts or page. This will list out the 5 recent posts of category id 31. So here we have used 2 parameters (category id, number of posts), we can also pass the order and order by parameter.

Code Explanation

On the above example, We have used 3 functions extract(), shortcode_atts() and get_posts() . extract() function is an inbuilt PHP function that is used to create array keys into variable and array values into variable value.

shortcode_atts() is used to combine the user’s attributes with default attributes. So as per our example, category id is only required while other parameters are optional so that all others are by default set in the function. Thus, when user-defined the optional attributes in shortcode at that time shortcode_atts() will check the user-defined attributes presence and replace it with the default. We hope you understood this.

get_posts() function is used to fetch the posts as array-based on passed arguments like numberposts, category, order, orderby, post_type, etc.

We loop through all the retrieved posts through get_posts() and echoed it.

That’s it for now. We hope this article helped you to learn add_shortcode() function in WordPress.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!

Leave a Comment