WPBeginner

Beginner's Guide for WordPress

  • Blog
    • Beginners Guide
    • News
    • Opinion
    • Showcase
    • Themes
    • Tutorials
    • WordPress Plugins
  • Start Here
    • How to Start a Blog
    • Create a Website
    • Start an Online Store
    • Best Website Builder
    • Email Marketing
    • WordPress Hosting
    • Business Name Ideas
  • Deals
    • Bluehost Coupon
    • SiteGround Coupon
    • WP Engine Coupon
    • HostGator Coupon
    • Domain.com Coupon
    • Constant Contact
    • View All Deals »
  • Glossary
  • Videos
  • Products
X
☰
Beginner's Guide for WordPress / Start your WordPress Blog in minutes
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

WPBeginner» Blog» Tutorials» How to Show Recent Posts by Category in WordPress

How to Show Recent Posts by Category in WordPress

Last updated on March 24th, 2015 by Editorial Staff
58 Shares
Share
Tweet
Share
Pin
Free WordPress Video Tutorials on YouTube by WPBeginner
How to Show Recent Posts by Category in WordPress

Have you ever wanted to showcase your recent posts from each category in your WordPress sidebar? Recently, one of our users asked us for an easy way to display recent posts from a specific category in WordPress sidebar widgets. In this article, we will cover how to show recent posts by category in your WordPress sidebar.

Posts by Category

Video Tutorial

Subscribe to WPBeginner

If you don’t like the video or need more instructions, then continue reading.

There are two ways to display recent posts by category in WordPress. The first method is fairly simple and beginner friendly because we will use a plugin to display recent posts by category in a widget (no coding necessary).

The second method uses a code snippet for our advanced DIY users, so you can display recent posts from a specific category without a plugin.

The only advantage to using the code method is that you are not dependent on a plugin, and you have a few more customization options. However the plugin method is EASY and has most of the customization options to satisfy 95% of the people such as show post thumbnail images, display post excerpt and control excerpt length, show the post date and number of comments, etc.

Having that said, let’s take a look how you can can show recent posts by category in your WordPress sidebar with the category post widget plugin.

Display Recent Posts by Category (Plugin Method)

First thing you need to do is install and activate the Category Posts Widget plugin.

Upon activation, you need to visit Appearance » Widgets, there you will notice the new Category Posts widget in the list of available widgets.

Simply drag and drop Category Posts widget to a sidebar where you want to display recent posts by category.

Category posts widget settings

The widget options are quite self explanatory. First you need to provide a title for the category posts section and choose a category. After that you can choose other display options like number of posts, excerpts, featured image, etc.

Once you are done, click the save button to store your widget settings. You can now visit your site to see recent posts by category in action.

Display Recent Posts by Category without a Plugin (Code Snippet)

In this method, we will use a code snippet to display recent posts from a category.

First you need to add this code in your theme’s functions.php file or a site-specific plugin.


function wpb_postsbycategory() {
// the query
$the_query = new WP_Query( array( 'category_name' => 'announcements', 'posts_per_page' => 10 ) ); 

// The Loop
if ( $the_query->have_posts() ) {
	$string .= '<ul class="postsbycategory widget_recent_entries">';
	while ( $the_query->have_posts() ) {
		$the_query->the_post();
			if ( has_post_thumbnail() ) {
			$string .= '<li>';
			$string .= '<a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_post_thumbnail($post_id, array( 50, 50) ) . get_the_title() .'</a></li>';
			} else { 
			// if no featured image is found
			$string .= '<li><a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_title() .'</a></li>';
			}
			}
	} else {
	// no posts found
}
$string .= '</ul>';

return $string;

/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('categoryposts', 'wpb_postsbycategory');

// Enable shortcodes in text widgets
add_filter('widget_text', 'do_shortcode');

Make sure that you replace 'announcements' with your own category slug.

This code simply queries WordPress to retrieve 10 posts from a specified category. It then displays the posts in a bulleted list. If a post has a featured image (post thumbnail), then it will show the featured image as well.

In the end, we created a shortcode 'categoryposts' and enabled shortcode in text widgets.

There are three ways of displaying the recent posts by category using this code snippet.

First, you can simply paste the following code anywhere in your desired template file location (such as footer.php, single.php, etc).

<?php wpb_postsbycategory() ?>

Second and third method relies on using the shortcode in the widget area or inside your posts / pages.

Simply visit Appearance » Widgets and add a text widget to your sidebar. Next add [categoryposts] shortcode in the text widget and save it. You can now preview your website to see recent posts by category in the sidebar.

If you want to show recent posts by categories on specific post or pages, then simply paste the shortcode in the post content area.

By default, your list may not look very good. You will need to use CSS to style the category posts list. You can use the code below as an starting point in your theme or child theme’s stylesheet.

ul.postsbycategory {
list-style-type: none;
}

.postsbycategory img {
float:left; 
padding:3px;
margin:3px;
border: 3px solid #EEE;
}

Posts from a category displayed with thumbnails

That’s all, we hope this article helped you display recent posts by category in WordPress sidebar. You may also want to check out these most wanted category hacks and plugins for WordPress.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Google+.

58 Shares
Share
Tweet
Share
Pin
Popular on WPBeginner Right Now!
  • How to Start Your Own Podcast (Step by Step)

    How to Start Your Own Podcast (Step by Step)

  • How to Fix the Error Establishing a Database Connection in WordPress

    How to Fix the Error Establishing a Database Connection in WordPress

  • Checklist

    Checklist: 15 Things You MUST DO Before Changing WordPress Themes

  • Google Analytics in WordPress

    How to Install Google Analytics in WordPress for Beginners

About the Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Trusted by over 1.3 million readers worldwide.

The Ultimate WordPress Toolkit

34 Comments

Leave a Reply
  1. Rob says:
    Feb 3, 2021 at 1:52 am

    If i have 10 categories, do i just paste the code snippet 10 times within functions.php
    and
    alter the ‘announcements’ for each of my slug for their category
    and
    Alter the “categoryposts” name for each code snippet so the shortcode knows which category posts should be displayed for which category

    I know its a few years old now but if be greta to know if this works

    Reply
    • WPBeginner Support says:
      Feb 3, 2021 at 9:55 am

      We have an updated article on this that you would want to take a look at below:

      https://www.wpbeginner.com/wp-tutorials/how-to-display-recent-posts-from-a-specific-category-in-wordpress/

      Reply
  2. Shelley Gammon says:
    Nov 2, 2018 at 2:07 pm

    Thank you so much for this tutorial. I worked perfectly as described. What if I want it to show the posts, not just links to the posts?

    Reply
  3. Andres says:
    Jun 1, 2017 at 7:06 pm

    I don’t know why $string didn’t work for me so I replace it for echo

    Reply
  4. Emeka says:
    Apr 30, 2017 at 6:49 am

    Thanks so much! this was exactly what I was looking for. Now my Blog looks more attractive. i love wpbeginner.com keep it up….

    Reply
    • WPBeginner Support says:
      Apr 30, 2017 at 3:14 pm

      Hey Emeka,

      Thanks for the kind words :) Don’t forget to join us on Twitter for more WordPress tips and tutorials.

      Reply
  5. Rebecca says:
    Apr 7, 2017 at 4:45 pm

    Hi, thanks for this! It’s exactly what I was looking for. When I pull in a post from a category anywhere on the page, it changes the content of the original post on the page. Any ideas why this is happening? I’m trying to place a featured posts in a sidebar and place this sidebar on the single post pages. Thanks for any help!

    Reply
  6. abdul alim says:
    Feb 27, 2017 at 3:34 am

    can i change shorcode name as I wise…?
    can I create this every category…?
    please tell me….

    Reply
  7. Kris says:
    Feb 11, 2017 at 7:03 am

    Thanks for this post! How would I go about adding excerpts to the code snippet?

    Reply
  8. Debra says:
    Oct 23, 2016 at 1:00 pm

    This is great. The posts by category worked perfectly. One question: Is there a way for it to display the posts in the category without showing an entry for the current post. For example, lets say there’s a category for cute animals and the current post is about cute puppies, is there a way to exclude the cute puppies link from the list of related posts? Hope that makes sense. thanks

    Reply
    • Rob Cheatham says:
      Dec 13, 2016 at 9:17 am

      Hi Debra, if you’re still struggling with this you can amend the query slightly. I have done the same and it is working well. Just adjust the code to be the following –

      $current_id = get_the_ID();
      $the_query = new WP_Query( array( ‘category_name’ => ‘services’, ‘posts_per_page’ => 10, ‘post__not_in’ => array($current_id) ) );

      Hope that helps.
      Rob

      Reply
  9. Arifa Rumpa says:
    Jul 24, 2016 at 6:02 am

    Thanks for your code. I have used it in y site. It works well to display my post in my wall.

    Reply
  10. Debby says:
    Jul 21, 2016 at 2:41 pm

    Thanks, it works great.
    I’ve tried to add pagination to the script like this:

    $paged = ( get_query_var(‘paged’) ) ? get_query_var(‘paged’) : 1;
    $query_args = array(
    ‘post_type’ => ‘post’,
    ‘category_name’ => ‘actueel’,
    ‘posts_per_page’ => 3,
    ‘paged’ => $paged
    );
    $the_query = new WP_Query( $query_args );

    Could you help me finish this code to make it work?

    Kind regards,
    Debby

    Reply
  11. Henrik says:
    Jul 18, 2016 at 3:49 pm

    Hi,

    Great tutorial and it works but I need to get the titles to show under the thumbnails, so do you have any good or hint how to do this in CSS?

    Thanks!

    Reply
    • WPBeginner Support says:
      Jul 19, 2016 at 12:59 pm

      If you are using the code method then you can simply display thumbnail before post title or excerpt.

      Reply
  12. ben says:
    May 27, 2016 at 1:48 pm

    hi,

    thanks for this its great! i want to also include the post meta. how would go about also displaying this?

    div.post-meta

    Reply
  13. Gos says:
    Apr 17, 2016 at 3:31 pm

    Looks good.. i wil try it
    On this page there is a section “More on wpbeginners now”
    looks the same but now with two colums… how can I achieve this layout ??

    Reply
  14. Jay says:
    Mar 15, 2016 at 12:03 pm

    In the code version, this bit of code cannot be reached because it comes after a return statement:

    /* Restore original Post Data */
    wp_reset_postdata();

    Reply
  15. James says:
    Jan 12, 2016 at 3:24 pm

    Great stuff! Works perfectly, exactly what I needed. I don’t like adding more plugins, because I have so many already, so the function code was very useful. Thanks so much!

    Reply
    • Muhammad Uzair says:
      Jan 19, 2016 at 2:26 am

      i try this code to add in functions.php but it did not work 4 me i have constructo Themes

      Reply
  16. Cliff says:
    Dec 3, 2015 at 9:32 pm

    Thanks. This is exactly waht i was looking for. Very useful!

    Reply
  17. Abubakar says:
    Nov 5, 2015 at 1:39 pm

    Nice post. It was working…

    Reply
  18. Santosh says:
    Sep 25, 2015 at 1:38 am

    Great! Thanks a lot!

    Reply
  19. plazma says:
    Jul 30, 2015 at 4:15 pm

    is it possible show multi categories slug with Code Snippet ?

    Reply
  20. Isaac Ohene says:
    May 8, 2015 at 4:29 am

    Works perfectly but I think if your are using the first method ; you need to echo the function else you get no results.

    Reply
  21. Darren says:
    May 7, 2015 at 9:04 am

    What part of the code do I need to delete to hide the images?

    I do not want to use display:none; in the CSS because the function appears to be still fetching the image.

    I just want to stop the PHP fetching the thumbnail altogether and just show titles.

    Thanks.

    Reply
    • Joeric says:
      May 27, 2015 at 3:03 pm

      You can remove get_the_post_thumbnail() portion to stop pulling out the thumbnail image per post.

      Reply
  22. DeBAAT says:
    Mar 26, 2015 at 3:35 am

    Very nice example. Thank you.

    Could you also add an attribute to the shortcode to enable the selection of the category in the widget? Instead of the hard-coded “announcemnts”. Such that I can use different widgets on different locations showing different categories?

    Reply
  23. Ronny says:
    Mar 1, 2015 at 3:43 am

    Hello, I can’t seem to get this to work in my site-specific plugin. I already have some code snippets there and they work perfectly, but adding the above code immediately disabled the plugin. Please what am I missing? …and thanks as usual for your very helpful tutorials.

    Reply
  24. WPBeginner Staff says:
    Feb 25, 2015 at 10:59 pm

    Thanks for the suggestion, duly noted.

    Reply
  25. WPBeginner Staff says:
    Feb 25, 2015 at 10:55 pm

    Glossary is a custom post type.

    Reply
  26. eshwar g says:
    Feb 25, 2015 at 5:54 am

    hi i’m new to wordpress, thanks to wpbeginner for teaching us for free. i wanna know how can we create menu permalink like ur page url https://www.wpbeginner.com/glossary/permalinks/ (glossary/permalinks). is glossary a post or category or page. can u pls explain this

    Reply
  27. mclanfranconi says:
    Feb 24, 2015 at 3:37 pm

    Excellent article .

    If you could write about some plugins or widgets to display categories with subcategories (rather than all kinds waterfall look ) or display with a drop-down menu, but from the sidebar , would be very grateful .

    Reply
  28. ohpress says:
    Feb 24, 2015 at 12:46 pm

    Funny, I literally did a search on your site for this last night. Glad to see you have the same plugin recommendation as your last article on this. I used it and it works great. Thank you.

    Reply

Leave a Reply Cancel reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Over 1,320,000+ Readers

Get fresh content from WPBeginner

Featured WordPress Plugin
All in One SEO
Improve website SEO rankings with AIOSEO plugin. Learn More »
How to Start a Blog How to Start a Blog
I need help with ...
Starting a
Blog
WordPress
Performance
WordPress
Security
WordPress
SEO
WordPress
Errors
Building an
Online Store
Useful WordPress Guides
    • 7 Best WordPress Backup Plugins Compared (Pros and Cons)
    • How to Fix the Error Establishing a Database Connection in WordPress
    • Why You Need a CDN for your WordPress Blog? [Infographic]
    • 30 Legit Ways to Make Money Online Blogging with WordPress
    • Self Hosted WordPress.org vs. Free WordPress.com [Infograph]
    • Free Recording: WordPress Workshop for Beginners
    • 24 Must Have WordPress Plugins for Business Websites
    • How to Properly Move Your Blog from WordPress.com to WordPress.org
    • 5 Best Contact Form Plugins for WordPress Compared
    • Which is the Best WordPress Popup Plugin? (Comparison)
    • Best WooCommerce Hosting in 2021 (Comparison)
    • How to Fix the Internal Server Error in WordPress
    • How to Install WordPress - Complete WordPress Installation Tutorial
    • Why You Should Start Building an Email List Right Away
    • How to Properly Move WordPress to a New Domain Without Losing SEO
    • How to Choose the Best WordPress Hosting for Your Website
    • How to Choose the Best Blogging Platform (Comparison)
    • WordPress Tutorials - 200+ Step by Step WordPress Tutorials
    • 5 Best WordPress Ecommerce Plugins Compared
    • 5 Best WordPress Membership Plugins (Compared)
    • 7 Best Email Marketing Services for Small Business (2021)
    • How to Choose the Best Domain Registrar (Compared)
    • The Truth About Shared WordPress Web Hosting
    • When Do You Really Need Managed WordPress Hosting?
    • 5 Best Drag and Drop WordPress Page Builders Compared
    • How to Switch from Blogger to WordPress without Losing Google Rankings
    • How to Properly Switch From Wix to WordPress (Step by Step)
    • How to Properly Move from Weebly to WordPress (Step by Step)
    • Do You Really Need a VPS? Best WordPress VPS Hosting Compared
    • How to Properly Move from Squarespace to WordPress
    • How to Register a Domain Name (+ tip to get it for FREE)
    • HostGator Review - An Honest Look at Speed & Uptime (2021)
    • SiteGround Reviews from 4464 Users & Our Experts (2021)
    • Bluehost Review from Real Users + Performance Stats (2021)
    • How Much Does It Really Cost to Build a WordPress Website?
    • How to Create an Email Newsletter the RIGHT WAY (Step by Step)
    • Free Business Name Generator (A.I Powered)
    • How to Create a Free Business Email Address in 5 Minutes (Step by Step)
    • How to Install Google Analytics in WordPress for Beginners
    • How to Move WordPress to a New Host or Server With No Downtime
    • Why is WordPress Free? What are the Costs? What is the Catch?
    • How to Make a Website in 2021 – Step by Step Guide
Deals & Coupons (view all)
Dreamhost
DreamHost Coupon
Get up to 67% OFF DreamHost's web hosting, plus a FREE domain of your choice.
OptinMonster
OptinMonster Coupon
Save 10% off on OptinMonster, the best lead generation plugin for WordPress.
Featured In
About WPBeginner®

WPBeginner is a free WordPress resource site for Beginners. WPBeginner was founded in July 2009 by Syed Balkhi. The main goal of this site is to provide quality tips, tricks, hacks, and other WordPress resources that allows WordPress beginners to improve their site(s).

Join our team: We are Hiring!

Site Links
  • About Us
  • Contact Us
  • FTC Disclosure
  • Privacy Policy
  • Terms of Service
  • Free Blog Setup
  • Free Business Tools
  • Growth Fund
Our Sites
  • OptinMonster
  • MonsterInsights
  • WPForms
  • SeedProd
  • Nameboy
  • RafflePress
  • Smash Balloon
  • AIOSEO

Copyright © 2009 - 2021 WPBeginner LLC. All Rights Reserved. WPBeginner® is a registered trademark.

Managed by Awesome Motive | WordPress hosting by SiteGround | WordPress Security by Sucuri.