In a default WordPress installation, the recent posts widget displays posts from all categories. But what if you want to display recent posts to that belong to specific categories? In this article, you’ll learn two methods of limiting recent posts by category:
- Using the Recent Posts Widget Extended plugin
- Editing your WordPress theme files
Using the Recent Posts Widget Extended plugin
Using a plugin is the simplest method of displaying recent posts from specific categories. Log in to your WordPress dashboard and go to Plugins > Add New. Type recent posts widget extended in the search field. In the search results, find Recent Posts Widget Extended and click Install Now.
When the plugin is installed, click Activate.
Next, go to Appearance > Widgets. In Available Widgets, click Recent Posts Extended and select Blog Sidebar. Click Add Widget.
Recent Posts Extended has several settings that you can choose from, but in this example we’re only setting the Limit to Category options. When you’re finished choose the categories, click Save.
Only the recent posts in the selected categories are now displayed in your site’s sidebar.
Editing your WordPress theme files
Another method of limiting recent posts to specific categories is to edit your WordPress theme files. You should only use this method if you’re comfortable editing files and adding PHP code. We recommend that you make a backup copy of the file before you edit it.
Before you begin editing files, you’ll need to find the ID of the categories you want to specify. Log in to your WordPress Dashboard and go to Posts > Categories. Hover your mouse pointer over the category and look at the URL displayed at the bottom of your browser window. The category ID is in the string taxonomy=category&tag_ID=[n]. For example, in the image below, our mouse pointer is hovered over the how-to category and the URL at the bottom of the browser includes taxonomy=category&tag_ID=2. This means that that how-to category ID is 2.
Next, go to Appearance > Editor and open the theme file where you want to display the recent posts in the specified category. Insert the following code, changing cat=2 in the first line to the correct category ID. When you’re finished editing the file, click Update File and test your site.
<?php $catquery = new WP_Query( 'cat=2&posts_per_page=5' ); ?> <ul> <?php while($catquery->have_posts()) : $catquery->the_post(); ?> <li> <a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a> </li> <?php endwhile; wp_reset_postdata(); ?> </ul>
If you have any questions or need help, you can always contact HostPapa Support by opening a support ticket. Details about how to open a support ticket are here.