Learn to create shortcodes in WordPress

In this post we will show an example on how the create a shortcode that shows your latest posts. Shortcodes are WordPress specific code that allow users easily add a functionality with just single line of code. As a developer you can create your own shortcodes that can extend either your theme’s or plugin’s functionality. The same shortcode provided in this article is being used on the front page of WPTipster.

Latest posts shortcode

We will create a shortcode that will extend our custom WordPress theme’s functionality, so we will include the code in the theme’s functions.php file. The shortcode will get the latest posts from our blog. Since the theme that we are developing uses Bootstrap framework, we want to style the posts based on this.

Basics of the shortcode

function awesome_shortcode() {
 return 'My awesome posts shortcode';
}
add_shortcode('awesome', 'awesome_shortcode');

This shortcode will return the string ‘My awesome posts shortcode’. Shortcode can be called with:

[awesome]

Adding parameters to the shortcode

Since we want to be able to add how many posts we want to get, we need to allow our shortcode function to accept parameters. We will also take into consideration an event where no parameters is given which is why we first check whether there are any parameters given with the shortcode.

function awesome_shortcode($atts = []) {
  if (!empty($atts['limit'])) {
    	$limit = $atts['limit']; 
    } else {
    	$limit = -1;
    }
 return 'My awesome posts shortcode';
}
add_shortcode('awesome', 'awesome_shortcode');

If a parameter limit is found, the function will take the value from the parameter. If not, it will take all the latest posts as -1 is to default value. Shortcode can be called with parameters like:

[awesome limit=2]

This would set the limit value to 2.

Adding the posts to the shortcode

While our awesome shortcode now takes parameters, it still only returns the same string. Lets get the latest posts as well.

function awesome_shortcode($atts = []) {
  if (!empty($atts['limit'])) {
    	$limit = $atts['limit']; 
    } else {
    	$limit = -1;
    }

/* Arguments to define what */
      $args = array(
        'numberposts'   => $limit, /* If empty, will default to -1 */
        'post_status'   => 'publish', /* We only want posts that are published */
        'post_type'     => 'post', /* Post type */
        'orderby'       => 'date', /* How to order posts */
        'order'         => 'DESC' /* Get the latest post first */
    );

 $posts = get_posts($args); /* Get the posts */

// Check that object is not empty
      if (!empty($posts)):

// Bootstrap row for all posts 
        $str = '<div id="latest-posts" class="row">';

// Loop through all posts 
        foreach ($posts as $post) {
        if (has_post_thumbnail($post)) { /* If post has thumbnail, get thumbnail url */
        	$img = get_the_post_thumbnail_url( $post->ID, $size = 'medium' );
        } else { /* If not, then use a placeholder image */
	    	$img = 'http://placehold.it/750x250" class="img-responsive';
	    }
      		$str .= '<div class="col-md-12"><a href="' . get_permalink($post->ID) . '"><img class="img-responsive" src="'.$img.'" alt="'.$post->post_title.'"></a><h3>'.$post->post_title.'</h3><a class="btn btn-primary btn-block" href="' . get_permalink($post->ID) . '">Read awesome article</a></div>';
       } /* Foreach loop ends */

        $str .= '</div>'; /* Close the bootstrap row */
    endif; 

    return $str; /* Return the whole string */
}
add_shortcode('awesome', 'awesome_shortcode');

And that’s it! Code can easily be applied to custom post types and pages as well. Just change the arguments and you are good to go.

Banner icon: Designed by Freepik