How to Display Recent Posts From a Specific Category in WordPress

6 min read 22-10-2024
How to Display Recent Posts From a Specific Category in WordPress

When it comes to blogging and managing content on your WordPress website, the categorization of your posts plays a pivotal role in enhancing user experience and engagement. Have you ever wondered how to display recent posts from a specific category on your WordPress site? You’re not alone! Many website owners, be it beginners or seasoned veterans, have sought ways to curate their content better and help users navigate through their categories effortlessly.

In this comprehensive guide, we will unravel the secrets of displaying recent posts from a particular category in WordPress. We’ll walk you through various methods, from using WordPress built-in features to advanced code snippets and plugins. Our objective is to ensure you have a firm grasp of the processes involved, and by the end, you’ll feel confident enough to implement this feature yourself.

Why Categorize Your Posts?

Before we dive into the how-to, let’s briefly discuss why categorizing your posts is essential. Categories act as an organizational tool that helps your readers find content that interests them quickly. For example, if you run a food blog, your categories might include “Desserts,” “Appetizers,” and “Main Dishes.” By displaying recent posts from these specific categories, you encourage users to explore more, enhancing their overall experience on your site.

In addition, search engines appreciate well-structured content. Having categorized posts can lead to better SEO rankings, meaning more traffic directed to your blog. You’re not only improving user experience but also aligning with best SEO practices!

Method 1: Using WordPress Default Features

Step 1: Creating a Category

If you haven't created the desired category yet, follow these simple steps:

  1. Log in to Your WordPress Dashboard: Navigate to yoursite.com/wp-admin.
  2. Go to Posts → Categories: On the left sidebar, click on 'Posts' and then 'Categories.'
  3. Add New Category: Fill out the details for your category (name, slug, and description) and click 'Add New Category.'

Step 2: Displaying Recent Posts via Widgets

WordPress offers various ways to display recent posts. One of the simplest is through widgets.

  1. Navigate to Appearance → Widgets: Here, you will see all available widgets.
  2. Add the ‘Recent Posts’ Widget: Find the ‘Recent Posts’ widget and drag it to your desired widget area (like the sidebar or footer).
  3. Customize Your Widget: Give it a title and set the number of posts to display. Unfortunately, the default widget shows all recent posts, but it’s a great starting point.

Step 3: Using the Custom HTML Widget

To filter posts by category directly in the widget, you'll need to use the Custom HTML widget with a shortcode, which we’ll dive into next.

Method 2: Using Shortcodes

Creating a Shortcode to Display Recent Posts

Shortcodes in WordPress allow you to add dynamic content to your posts and pages quickly. Follow these steps to create a shortcode for your recent posts in a specific category:

  1. Open the Theme’s Functions.php File: This file is crucial for adding custom PHP code. Go to Appearance → Theme Editor and select the ‘functions.php’ file.

  2. Add the Following Code:

    function recent_posts_by_category($atts) {
        $atts = shortcode_atts(
            array(
                'category' => '',
                'posts' => 5,
            ),
            $atts,
            'recent_posts'
        );
    
        $query = new WP_Query(array(
            'category_name' => sanitize_text_field($atts['category']),
            'posts_per_page' => intval($atts['posts']),
        ));
    
        if ($query->have_posts()) {
            $output = '<ul>';
            while ($query->have_posts()) {
                $query->the_post();
                $output .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
            }
            $output .= '</ul>';
            wp_reset_postdata();
            return $output;
        } else {
            return 'No recent posts found.';
        }
    }
    add_shortcode('recent_posts', 'recent_posts_by_category');
    
  3. Save the Changes: Ensure to save any changes before leaving the Theme Editor.

Step 4: Using the Shortcode in Your Post/Page

Now that your shortcode is ready, you can display recent posts from a specific category wherever you want.

  1. Edit the Post or Page: Go to the post or page where you want the recent posts to appear.
  2. Add the Shortcode: Insert [recent_posts category="your-category-slug" posts="5"]. Replace “your-category-slug” with the actual slug of the category you want to display.

Method 3: Utilizing a Plugin

If you prefer a more user-friendly method without delving into code, there are several plugins available. Below, we will discuss one of the most popular options.

Using the ‘Recent Posts Widget Extended’ Plugin

This plugin allows for displaying recent posts from specific categories easily.

  1. Install the Plugin: Navigate to Plugins → Add New, search for ‘Recent Posts Widget Extended,’ and install and activate it.
  2. Add the Widget: Go back to Appearance → Widgets and find the ‘Recent Posts Extended’ widget. Drag it to your desired widget area.
  3. Customize the Settings: Here, you’ll have options to filter by category, choose the number of posts, display thumbnails, and much more!

Method 4: Displaying Recent Posts via Custom Page Templates

If you want more control over how the posts are displayed, creating a custom page template can be a game-changer.

Step 1: Create a Custom Template

  1. Access Your Theme Files: Go to Appearance → Theme Editor, and choose ‘theme-name’ directory.

  2. Create a New File: Name it recent-posts.php or similar.

  3. Insert the Following Code:

    <?php
    /* Template Name: Recent Posts by Category */
    get_header(); ?>
    <div class="content-area">
        <main class="site-main">
            <?php
            $args = array(
                'category_name' => 'your-category-slug',
                'posts_per_page' => 5,
            );
            $recent_posts = new WP_Query($args);
            if ($recent_posts->have_posts()) {
                while ($recent_posts->have_posts()) {
                    $recent_posts->the_post();
                    ?>
                    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                    <p><?php the_excerpt(); ?></p>
                    <?php
                }
                wp_reset_postdata();
            } else {
                echo 'No recent posts found.';
            }
            ?>
        </main>
    </div>
    <?php get_footer(); ?>
    

Step 2: Create a New Page Using the Template

  1. Navigate to Pages → Add New: Create a new page where you’d like to display the posts.
  2. Select Your Template: On the right sidebar, under ‘Page Attributes,’ select ‘Recent Posts by Category’ and publish your page.

Method 5: Displaying Recent Posts in the Theme’s Sidebar or Footer

For a more permanent display of recent posts by category, consider including them in your theme’s sidebar or footer.

Step 1: Editing Sidebar.php or Footer.php

  1. Go to Appearance → Theme Editor: Click on sidebar.php or footer.php.
  2. Insert the Code: You can include a similar code snippet as used above in the custom template section. This way, it’s displayed in your sidebar or footer globally.

Example Code:

$args = array(
    'category_name' => 'your-category-slug',
    'posts_per_page' => 5,
);
$recent_posts = new WP_Query($args);
if ($recent_posts->have_posts()) {
    echo '<ul>';
    while ($recent_posts->have_posts()) {
        $recent_posts->the_post();
        echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
    }
    echo '</ul>';
    wp_reset_postdata();
} else {
    echo 'No recent posts found.';
}

Conclusion

Displaying recent posts from a specific category in WordPress can elevate the user experience on your site. By utilizing WordPress’ built-in features, creating custom shortcodes, or employing plugins, you can easily showcase relevant content to your visitors.

Remember, effective categorization and displaying recent posts not only keeps your site organized but also helps retain visitors, encouraging them to explore more. We hope this guide has empowered you to implement this feature seamlessly. Whether you choose the coding route or a plugin, you now have the tools and knowledge to enhance your WordPress website.

FAQs

1. Can I display posts from multiple categories?
Yes! You can modify the code snippets provided to include multiple category slugs separated by commas.

2. Are there any performance concerns when using plugins?
Plugins can impact performance, but choosing reputable, well-maintained plugins usually leads to minimal impact.

3. What if I don’t want to touch code?
Using a plugin is a great way to display posts from a specific category without any coding knowledge.

4. Can I style the output of my recent posts?
Absolutely! You can add CSS styles to customize the appearance of your recent posts in the template or widget settings.

5. Is it possible to use a page builder to display recent posts?
Yes! Many page builders, like Elementor or WPBakery, have modules that allow you to display posts filtered by category easily.

By understanding these methods, you can tailor the content display to fit your site’s needs. Happy blogging!