Display Recent Posts Anywhere in your Theme

Posted on

By Michael Fields

I recently came up with this solution to a question asked on wpQuestions.com. The following code can be used on any template of your WordPress theme and will display the most recent 5 posts with a title and an except:

$latest = get_posts( 'numberposts=5' );
foreach( $latest as $post ) {
	setup_postdata( $post );
	$url = get_permalink( $post->ID );
	$title = apply_filters( 'the_title', get_the_title() );
	$excerpt = apply_filters( 'the_excerpt', get_the_excerpt() );
	print "\n\t" . '<h2><a href="' . $url . '">' . $title . '</a></h2>';
	print "\n\t" . $excerpt;
}

By default WordPress will append the following series of characters to the excerpt: [...] If you find this undesirable, it is very easy to filter the this string and customize it to your liking. The following example will replace [...] with … more with the text more linked to the full post:

add_filter('excerpt_more', 'new_excerpt_more');
function new_excerpt_more( $more ) {
	global $post;
	$url = get_permalink( $post->ID );
	return '... <a href="' . $url . '">more</a>';
}

To replace the end of every excerpt with our new more link you will want to add this code to your theme’s functions.php file. If, however, you only want to change it on certain template views (category, tag, page, etc) you should add it to the corresponding template file.

Share your thoughts

*

Fork me on GitHub