WordPress: listing categories with the most recent posts

WordPress: listing categories with the most recent posts

How to create a nested list of WordPress categories featuring the most recent posts and the number of posts of each category. Ideal for an archive page.

A common feature requested when creating a WordPress archive page is to display all the site categories with the most recent posts for each category. Let's see how to implement this feature.

The following function, to be inserted in your functions.php file, generates a nested unordered list containing the name and the link of each category followed by the total number of posts published under the current category, plus the most recent posts:

function display_cats_with_posts() {
	
	$cats = get_categories();
	$html = '<ul id="archive-list">' . "\n";
	
	foreach($cats as $cat) {
		
		$id = $cat->cat_ID;
		$posts_no = $cat->category_count;
		$name = $cat->cat_name;
		$link = get_category_link( $cat->term_id );
		
		$html .= '<li><h3><a href="'. $link . '">' . $name . '</a><span> (' . $posts_no . ' post)</span></h3>';
		$html .= '<ul>' . "\n";
		$query = new WP_Query(array('cat' => $id, 'posts_per_page' => 10));
		
		while($query->have_posts()) {
			
			$query->the_post();
			
			$html .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>' . "\n";
			
			
		}
		
		wp_reset_query();
		
		$html .= '</ul>' . "\n";
		$html .= '</li>' . "\n";
		
		
	}
	
	$html .= '</ul>' . "\n";
	
	return $html;
	
}

The core of our function is made up by the get_categories() WordPress function which returns an array of category objects containing all the information we need.