How to display the 5 recent posts from a specific category on a WordPress page

To display the 5 latest posts from a specific category on a WordPress page, you can create a custom page template and use a custom WP_Query loop to fetch the desired posts. Follow these steps:

  1. In your WordPress theme folder, create a new file and name it page-latest-posts.php or any other name you prefer.
  2. Add the following code at the beginning of the page-latest-posts.php file:
<?php
/*
Template Name: Latest Posts from Specific Category
*/
?>

This code defines the file as a custom page template with the name “Latest Posts from Specific Category.”

  1. Next, copy the contents of your theme’s page.php file or a similar template file into the page-latest-posts.php file, just below the code you added in step 2.
  2. Locate the main loop in the copied code, which usually starts with if ( have_posts() ) : and ends with endif;. Replace this loop with the following custom WP_Query loop:
<?php
// Replace 'your-category-slug' with the slug of the specific category
$category_slug = 'your-category-slug';
$category = get_category_by_slug($category_slug);

// Check if the category exists
if ($category) {
// Create a new WP_Query to fetch the latest 5 posts from the specific category
$latest_posts = new WP_Query(array(
'category_name' => $category_slug,
'posts_per_page' => 5,
));

// The custom loop to display the latest posts
if ($latest_posts->have_posts()) :
while ($latest_posts->have_posts()) : $latest_posts->the_post();
// Display the post title and link
echo '<h2><a href="' . get_permalink() . '">' . get_the_title() . '</a></h2>';

// Display the post content or excerpt
the_content(); // or the_excerpt();

endwhile;
wp_reset_postdata(); // Reset the global post object
else :
echo '<p>No posts found in the specified category.</p>';
endif;
} else {
echo '<p>The specified category does not exist.</p>';
}
?>

Replace ‘your-category-slug’ with the slug of the specific category you want to fetch the latest posts from.

  1. Save the page-latest-posts.php file and upload it to your theme folder if necessary.
  2. In your WordPress admin dashboard, go to “Pages” > “Add New” to create a new page.
  3. In the “Page Attributes” box on the right side, select the “Latest Posts from Specific Category” template from the “Template” dropdown menu.
  4. Publish the page, and the 5 latest posts from the specified category will be displayed on it.

Remember to always backup your files before making any changes, and test your changes on a staging site or local development environment before applying them to your live site.

Leave a Reply

Your email address will not be published. Required fields are marked *