Create WordPress Shortcode to Display Posts from Categories

In WordPress, it’s always fun to use shortcodes. They allow you to do so much with just a piece of code.

In this article, we will take a look into creating a WordPress shortcode to display posts from a category or multiple categories by category id and name.

But before jumping into this, you should be clear about the use of parameters and attributes in the shortcode to easily understand the code given below.

I have written a detailed article about creating shortcodes with parameters and attributes, where I have outlined the use of multiple parameters and attributes in shortcodes.

So at this point, I am assuming you are aware of the use of parameters and attributes in the shortcode. Now let’s move further with this article.

Create Shortcode to Display Posts From a Category By Category ID

To display posts from a particular category follow the steps:

  1. Copy the below code snippet and add it in functions.php file located at wp-content/themes/your-theme/.
    // Creating Shortcodes to display posts from category
    function diwp_shortcode_display_post($attr, $content = null){
    
    	global $post;
    
    	// Defining Shortcode's Attributes
    	$shortcode_args = shortcode_atts(
    						array(
    								'cat'	 => '',
    								'num'	 => '5',
    								'order'  => 'desc'
    					    ), $attr);	
    	
    	// array with query arguments
    	$args = array(
    					'cat'		 	 => $shortcode_args['cat'],
    					'posts_per_page' => $shortcode_args['num'],
    					'order'          => $shortcode_args['order'],
    					
    				 );
    
    	
    	$recent_posts = get_posts($args);
    
    	$output = '<ul>';
    
    	foreach ($recent_posts as $post) :
    		
    		setup_postdata($post);
    
    		$output .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';	
    
    
    	endforeach;	
    	
    	wp_reset_postdata();
    
    	$output .= '</ul>';
    	
    	return $output;
    
    }
    
    add_shortcode( 'diwp_recent_posts', 'diwp_shortcode_display_post' );
    
    
  2. Then add this shortcode in page, post, or widgets by passing category id and other parameters in it.
    [diwp_recent_posts cat="16" num="3" order="asc"]
    
    • cat = Category id for which you want to display posts.
    • num = Number of posts to display per page.
    • order = order of posts to display, either ASC or DESC.

    If you want to add shortcode in your theme’s file or any specific template file then add it with the below code.

    <?php echo do_shortcode('[diwp_recent_posts cat="16" num="3" order="asc"]'); ?>
    
  3. This above code will display you the posts from the category which has id = “16”. Like in the image below you can see the output.
    create-shortcode-to-display-recent-posts-from-categories

So by using the above shortcode, you can easily display posts from any category. All you have to do is just pass the category id within cat attribute.

If you don’t pass category id in the shortcode or use default shortcode [diwp_recent_posts] then it will display posts from the default category (which has id = 1).

Create Shortcode to Display Posts from a Category by Category Name

If you want to display posts from a category by its name instead of ID. then you can use the same function and shortcode. All you have to do is, instead of cat use category_name in the $args array like given below.

// array with query arguments
$args = array(
	'category_name'   => $shortcode_args['cat'],
	'posts_per_page'   => $shortcode_args['num'],
	'order'                    => $shortcode_args['order'],
 );

And in the shortcode, instead of category Id use category name like in the example below.

[diwp_recent_posts cat="WP Tutorials" num="3" order="asc"]

And that’s it. The above shortcode will display the posts from a category by its name. So this will display posts from the category WP Tutorials as shown in the below image.

create-shortcode-to-display-recent-posts-from-categories-2

So as of now, you have learned about display posts from a specific category but what if you want to display posts from multiple categories.

Don’t worry, I am going to cover that as well in this article.

Create Shortcode to Display Posts from Multiple Categories

Again the above function and shortcode will be the same for displaying posts from multiple categories, but you have to make one change in your function.

// array with query arguments
	$args = array(
		'cat'	=> array($shortcode_args['cat']),
		'posts_per_page' => $shortcode_args['num'],
		'order'          => $shortcode_args['order'],
	 );

In the query arguments $args, for cat parameter, you have to pass the value as an array. So this can take multiple values.

And after doing that, add the below shortcode to display posts from different categories.

[diwp_recent_posts cat="16,17" num="4" order="desc"]

In the above shortcode, I have passed the ID of two categories as values in the cat parameter. So this will display posts from the categories, whose ids are 16 and 17.

I hope this article helped you to learn about creating shortcodes to display posts from a category or from multiple categories.

Owner of diveinwp.com, solely responsible for creating helpful, informative content about WordPress, a fulltime WordPress developer with 8+ years of hands-on experience in WordPress design and development.

7 thoughts on “Create WordPress Shortcode to Display Posts from Categories”

  1. Dear Bhuvnesh,

    thank you for sharing this post :)!
    I heave a question, how can I implement in this code adding of thumbnails and short description of a posts in defined category?

    thank you in advance

    1. Bhuvnesh Shrivastava

      You have to use get_the_post_thumbnail() function to get the image and get_the_excerpt() function to get the short description for the post. You can also watch the video embed in this post above, I have explained that in the Video.

  2. Hi Bhuvnesh,

    I’ve been trying out this method but where I’ve implemented the shortcode it is showing all posts, not just the one’s in the categories I’ve specified. Do you have any suggestions on what might be going wrong?

    1. Bhuvnesh Shrivastava

      Hi David,

      To display posts from specific categories you have to pass category name or id. you can check out the code for that, I have already mentioned that code above.

  3. Hi thanks for this I am having issues with trying to add a custom taxonomy and the category.
    I changed it to have ‘category_name’ => ”, and it works well just can’t seem to add the taxonomy. Do you have any suggestions? Thanks.

    1. Bhuvnesh Shrivastava

      Hi Theresa,

      To get the results as per taxonomy, you have to run taxonomy query. to do that you can pass ‘tax_query’ inside the array of arguments for WP_Query. something like:

      $args = array(
          'post_type' => 'post', // or your post type
          'tax_query' => array(
              array(
                  'taxonomy' => 'recipes', // or your taxonomy
                  'field'    => 'slug',
                  'terms'    => 'drinks', // or your terms
              ),
          ),
      );
      $query = new WP_Query( $args );
      

      Let me know if you still have any issue.

Comments are closed.