Today, I’d like to share a neat trick for WordPress. When managing a WordPress site or blog, you might want to provide fresh information to your readers beyond just listing posts. In such cases, displaying only the latest posts for each category can be highly effective.
This guide will show you how to retrieve and display a list of categories along with the latest post for each category in WordPress.
Preparation to Display Latest Posts by Category
Let’s create a custom template for a static page. Follow these steps:
- File name: page-catlist.php
- Template Name: Latest Posts by Category TPL
Prepare these in the theme directory. The content of the PHP file (page-catlist.php) is as follows:
<ul>
<?php
$args = array(
'parent' => 0, // Parent category
'orderby' => 'term_order',
'order' => 'ASC'
);
$categories = get_categories( $args ); // Retrieve category list information
foreach( $categories as $category ) :
// Retrieve the latest post for each category by slug
$data = get_posts('post_type=post&order=DESC&orderby=date&showposts=1&category_name='.$category->category_nicename);
if(isset($data[0])) {
?>
<li style="list-style:none; padding-bottom: 20px;">
<h4><?php echo $category->cat_name; ?></h4>
<a href="<?php echo get_permalink($data[0]->ID); ?>">
<?php echo date('Y.m.d', strtotime($data[0]->post_date)); ?>
<br>
<?php echo $data[0]->post_title; ?>
</a>
</li>
<?php
}//end if
endforeach;
?>
</ul>
With this code, you can list the latest post for each category on your WordPress site.
Processing Flow in the Static Page for Retrieving Latest Posts by Category
This method displays information in the following sequence:
- Retrieve the current category list (parent categories only).
- Loop through the retrieved category list.
- Specify the category slug and retrieve the latest post.
- Display the category name, latest post link, date, and title.
“Latest Posts by Category” Demo Page
After implementing this method on our site, we found it was highly effective in helping readers quickly access the latest information. It was very well-received. If you’re interested, check out the demo page below:
“Latest Posts by Category” Demo Page
Summary
By using the method introduced in this guide, you can significantly enhance the usability of your blog by making it easier for readers to find the latest posts. A little creativity with WordPress can make a big difference in your blog management. Give it a try and make your blog even more appealing!
※ Please use this method at your own discretion.