How to Display Recent Posts From a Specific Category in WordPress

21 hours ago, WordPress Tutorials, 1 Views
How to Display Recent Posts From A Specific Category In WordPress

Introduction: Why Display Recent Posts From a Specific Category?

WordPress, by default, displays blog posts in reverse chronological order. While this is a standard practice, website owners often need more control over how content is presented. One common requirement is to showcase recent posts from a specific category, highlighting particular areas of expertise, promoting specific product lines, or simply improving user navigation and engagement. This targeted approach offers several benefits:

  • Improved User Experience: Directing users to content they’re most likely interested in.
  • Increased Engagement: Encouraging users to explore related articles within a chosen category.
  • Content Promotion: Highlighting specific topics or products.
  • Better Navigation: Guiding users through a structured website.
  • Enhanced SEO: Reinforcing topical relevance and improving internal linking.

Displaying recent posts from a specific category is achievable through various methods, ranging from simple plugins to custom code solutions. The choice depends on your technical skill level, desired level of customization, and budget.

Method 1: Using WordPress Plugins

The easiest and most beginner-friendly way to display recent posts from a specific category is by using a WordPress plugin. Numerous plugins are available in the WordPress repository, each offering slightly different features and functionalities. Here are some popular options:

  • Recent Posts Widget With Thumbnails: A widely used plugin that allows you to display recent posts with thumbnails, excerpts, and category filtering.
  • Display Posts: A powerful plugin with shortcode support, enabling you to display posts from specific categories, tags, or custom taxonomies. Offers extensive customization options.
  • Category Posts Widget: A simple and effective widget designed specifically for displaying recent posts from a chosen category.
  • Advanced Post Queries: Allows you to create custom queries based on categories, tags, authors, and other criteria, and display the results using a widget or shortcode.

**Installation and Configuration:**

The installation process for these plugins is similar:

1. Log in to your WordPress dashboard.
2. Navigate to “Plugins” > “Add New.”
3. Search for the desired plugin by name.
4. Click “Install Now” and then “Activate.”

Once activated, the plugin will typically add a new widget or provide a shortcode that you can use to display the recent posts.

**Example: Using Recent Posts Widget With Thumbnails**

1. After activating the plugin, go to “Appearance” > “Widgets.”
2. Drag the “Recent Posts Widget With Thumbnails” widget to your desired sidebar or widget area.
3. Configure the widget settings:

  • Title: Enter a title for the widget (e.g., “Recent News,” “Featured Articles”).
  • Number of Posts: Specify the number of recent posts to display.
  • Display Thumbnails: Enable or disable the display of thumbnails.
  • Thumbnail Size: Choose the desired thumbnail size.
  • Display Post Excerpt: Enable or disable the display of post excerpts.
  • Excerpt Length: Set the maximum length of the excerpt.
  • Category: Select the specific category from which to display posts.

4. Save the widget settings.

The widget will now display recent posts from the selected category in the designated area of your website. The visual appearance and customization options will vary depending on the specific plugin you choose. Always refer to the plugin’s documentation for detailed instructions.

Method 2: Using WordPress Shortcodes

Shortcodes provide a flexible way to embed dynamic content within posts, pages, and widgets. Some themes and plugins offer shortcodes specifically designed for displaying recent posts from a category. The “Display Posts” plugin mentioned earlier is a prime example.

**Using the Display Posts Plugin:**

After installing and activating the Display Posts plugin, you can use its shortcode to display recent posts from a specific category. The basic syntax is:

`[display-posts category=”category-slug” posts_per_page=”5″]`

Replace `”category-slug”` with the actual slug of the category you want to display and `”5″` with the desired number of posts.

**Finding the Category Slug:**

1. Go to “Posts” > “Categories.”
2. Hover over the category you want to use.
3. Look at the URL in your browser’s status bar. The category slug is usually the last part of the URL after `tag_ID=`.
4. Alternatively, click “Edit” on the category and find the slug field.

**Customization Options:**

The Display Posts plugin offers numerous customization options that can be added to the shortcode:

  • posts_per_page: The number of posts to display (default: 10).
  • offset: The number of posts to skip (useful for pagination).
  • orderby: The order in which to display posts (e.g., “date,” “title,” “rand”).
  • order: The sorting order (“ASC” for ascending, “DESC” for descending).
  • include_excerpt: Whether to display the post excerpt (default: false).
  • excerpt_length: The length of the excerpt (in words).
  • image_size: The size of the featured image (e.g., “thumbnail,” “medium,” “large,” “full”).
  • wrapper: The HTML tag to wrap the posts in (default: ul).
  • wrapper_class: The CSS class to add to the wrapper tag.
  • inner_wrapper: The HTML tag to wrap each post in (default: li).

**Example:**

To display 3 recent posts from the “technology” category with thumbnails and excerpts, you would use the following shortcode:

`[display-posts category=”technology” posts_per_page=”3″ include_excerpt=”true” image_size=”thumbnail”]`

Place this shortcode within a post, page, or text widget to display the desired content.

Method 3: Custom Code (Using `WP_Query`)

For more advanced users who want greater control over the output, you can use custom code to query and display recent posts from a specific category. This method involves using the `WP_Query` class in WordPress.

**Creating a Custom Function:**

You can create a custom function in your theme’s `functions.php` file (or a custom plugin) to handle the query and display the posts. Be extremely careful when editing `functions.php`, as errors can break your site. Consider using a child theme to avoid losing changes during theme updates.

Here’s an example function:

“`php
function display_recent_category_posts($category_slug, $num_posts = 5) {
$args = array(
‘category_name’ => $category_slug,
‘posts_per_page’ => $num_posts,
‘orderby’ => ‘date’,
‘order’ => ‘DESC’
);

$the_query = new WP_Query($args);

if ($the_query->have_posts()) {
echo ‘

‘;
wp_reset_postdata(); // Restore original Post Data
} else {
echo ‘

No posts found in this category.

‘;
}
}
“`

**Explanation:**

* `display_recent_category_posts($category_slug, $num_posts = 5)`: Defines a function that takes the category slug and the number of posts to display as arguments. The number of posts defaults to 5 if not specified.
* `$args = array(…)`: Creates an array of arguments for the `WP_Query` class.
* `’category_name’ => $category_slug`: Specifies the category to query based on its slug.
* `’posts_per_page’ => $num_posts`: Sets the number of posts to retrieve.
* `’orderby’ => ‘date’`: Orders the posts by date.
* `’order’ => ‘DESC’`: Sorts the posts in descending order (newest first).
* `$the_query = new WP_Query($args)`: Creates a new instance of the `WP_Query` class with the specified arguments.
* `if ($the_query->have_posts())`: Checks if there are any posts matching the query.
* `echo ‘

    ‘;`: Opens an unordered list to display the posts.
    * `while ($the_query->have_posts())`: Loops through each post found by the query.
    * `$the_query->the_post()`: Sets up the post data for the current post in the loop.
    * `echo ‘

  • ‘ . get_the_title() . ‘
  • ‘;`: Displays a list item with a link to the post’s permalink and the post’s title.
    * `echo ‘

‘;`: Closes the unordered list.
* `wp_reset_postdata()`: Restores the original post data after the custom query to avoid conflicts with the main query.
* `else { echo ‘

No posts found in this category.

‘; }`: Displays a message if no posts are found in the specified category.

**Using the Custom Function:**

To use the function, call it from your theme’s template files (e.g., `sidebar.php`, `page.php`) or from a text widget using a plugin like “Shortcode Widget.”

Example:

``

This code will display 3 recent posts from the “technology” category.

**Customizing the Output:**

You can customize the output of the function to include thumbnails, excerpts, or other information by modifying the code within the `while` loop. For example, to add a thumbnail, you could use the `get_the_post_thumbnail()` function:

“`php
echo ‘

  • ‘ . get_the_post_thumbnail(‘thumbnail’) . get_the_title() . ‘
  • ‘;
    “`

    **Important Considerations:**

    * Always use a child theme when modifying your theme’s files to avoid losing changes during theme updates.
    * Be careful when editing the `functions.php` file, as errors can break your site.
    * Properly escape output to prevent security vulnerabilities (e.g., using `esc_url()` and `esc_html()`).

    Method 4: Using Gutenberg Blocks

    If you are using the Gutenberg block editor, some blocks can display recent posts from a specific category directly within your pages and posts.

    **Utilizing the “Latest Posts” Block:**

    WordPress comes with a “Latest Posts” block that can be customized to filter by category.

    1. In your Gutenberg editor, add a “Latest Posts” block.
    2. In the block settings on the right-hand side, you’ll find options to:

    • Display as a list or grid.
    • Show post content (excerpt).
    • Display post date.
    • Show featured image.
    • Filter by category.

    3. Use the category filter to select the specific category you want to display posts from.

    **Limitations:**

    The built-in “Latest Posts” block has limited customization options. If you need more advanced features, such as custom layouts or specific meta information, you might consider using a plugin that provides more flexible Gutenberg blocks.

    **Plugins for Enhanced Gutenberg Blocks:**

    Some plugins enhance the Gutenberg editor with more advanced block options for displaying posts:

    • Kadence Blocks: Offers a “Post Grid / List” block with extensive customization options, including category filtering.
    • Ultimate Addons for Gutenberg: Provides a “Post Grid” block with various layout options and category filtering.
    • Stackable: Features a “Posts” block with advanced customization features and category filtering.

    These plugins typically offer more control over the layout, styling, and content displayed within the post blocks.

    Choosing the Right Method

    The best method for displaying recent posts from a specific category depends on your specific needs and technical skills:

    • Beginners: Plugins offer the easiest and most straightforward solution.
    • Users comfortable with shortcodes: Plugins with shortcode support provide flexibility and customization options.
    • Developers: Custom code using `WP_Query` allows for maximum control over the output.
    • Gutenberg users: The built-in “Latest Posts” block or enhanced block plugins can be convenient for displaying posts within pages and posts.

    Consider the level of customization required, the ease of implementation, and the long-term maintainability of the solution when making your choice. Always back up your website before making significant changes to your theme or installing new plugins.