Display the Latest Posts in WordPress

Learn how-to display the latest posts in WordPress. Display X amount of posts and learn how-to make the list group into a Bootstrap panel.

Display the Latest Posts in WordPress
Photo by Fikret tozak / Unsplash

The blog page, typically the homepage, will display all of the latest posts. You can set how many will show using a query or through your administration panel. However, what about other parts of your website, like the 404 page, category pages, posts, and pages? You may want to display the latest posts in one (1) or all of these parts.

You can display the latest posts in WordPress using only five (5) lines of code (7, if you count the PHP syntax). You can easily customize the code so that it displays X posts or stylize it the way you want. Let me show you how.

<?php
	$args = array( 'numberposts' => '5' );
	$recent_posts = wp_get_recent_posts( $args );
	foreach( $recent_posts as $recent ){
		echo ' <a href="' . get_permalink($recent["ID"]) . '" title="'.esc_attr($recent["post_title"]).'" >' .   $recent["post_title"].'</a>';
	}
?>

The above code snippet is nothing fancy and will show the last five (5) posts. You can change how many posts are displayed by changing '5' on line two (2) of the above code snippet.

Add Some Style

You can quickly and easily stylize the above code snippet by wrapping it in HTML and / or adding HTML to line five (5), which is how each post will be outputted. Here is an example of how to make the list into an unordered HTML list:

<?php
	echo '<ul>';
	$args = array( 'numberposts' => '5' );
	$recent_posts = wp_get_recent_posts( $args );
	foreach( $recent_posts as $recent ){
		echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="'.esc_attr($recent["post_title"]).'" >' .   $recent["post_title"].'</a></li>';
	}
	echo '</ul>';	
?>

As you can see, I wrapped everything in <ul></ul> HTML tags and each posts will be wrapped in <li></li> HTML tags. You can of course add CSS class(es) to the <ul></ul> and <li></li> HTML tags, for more styling and easy appearance integration to your website.

Bootstrap Panel Style

Now, taking the above example, we can turn it into a Twitter Bootstrap list group panel. The code snippet would be:

<?php
	echo '<div class="panel panel-default"><div class="panel-heading">Last Five Posts</div><div class="panel-body"><p>Here are the latest posts:</p></div><ul class="list-group nav">';
	$args = array( 'numberposts' => '5' );
	$recent_posts = wp_get_recent_posts( $args );
	foreach( $recent_posts as $recent ){
		echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="'.esc_attr($recent["post_title"]).'" >' .   $recent["post_title"].'</a></li>';
	}
	echo '</ul></div>';	
?>

This web page uses this code snippet. So, if you want an example, look to the right side for โ€œLast Five Posts.โ€