WordPress: How to show recent posts in your post or page without using plugin?

If you want to display some recent posts in your WordPress post or page, you can use a plugin to do that. There are many plugins out there which can help you. You can easily find them using Google.

However, if you don’t like to install too many plugins in your WordPress site, you can do the job yourself by using some small PHP scripts. To display recent posts in a post or page, we have to use shortcode. We will write a function to get list of recent posts and create a shortcode for that function.

WordPress: How to show recent posts in your post or page without using plugin?

Don’t know how to code with PHP? Don’t worry! I did it for you. You just have to copy the code below, then paste it at the end of your theme functions file (functions.php) and save it.

//Get recent posts
function my_recent_posts_shortcode($atts){
	extract(shortcode_atts(array('posts' => 5,), $atts));
	$q = new WP_Query(
   	array( 'orderby' => 'date', 'posts_per_page' => $posts)
 	);
	$list = '<ul>';
	while($q->have_posts()) : $q->the_post();
 		$list .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
	endwhile;
	wp_reset_query();
	return $list . '</ul>';
}
//Add recent posts shortcode
add_shortcode('recent-posts', 'my_recent_posts_shortcode');

Now, you can show a list of recent posts in your post or page by using the shorcode:

[recent-posts]

The shortcode will show your last 5 posts by default. If you want to show a different number of posts, you have to set a value for the posts parameter. To show 10 latest posts, the shorcode will look like this:

[recent-posts posts="10"]

I hope you like it. Enjoy!

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on RedditShare on StumbleUponShare on LinkedInPin on Pinterest
Blogging,
ExoClick
About Nhut Le
Hello! My name is Nhut Le. I'm currently a software developer. You can subscribe to my RSS to get instant updates delivered to your email.