Make recent posts shortcode easily in wordpress, and use shortcode in posts, widget, anywhere! easy way to make recent posts shortcode.

How To Make Recent Posts Shortcode?

Using WordPress Shortcode API and wp_get_recent_posts() function we will make recent posts shortcode.

Recent Posts Function

Copy recent posts function code and paste it in your functions.php file.

/* Recent Posts Function */
function custom_recent_posts( $number = 3 ){ // default is 3 posts

	$latest_post_args = array( 'numberposts' => $number, 'post_type' => 'post', 'post_status' => 'publish' );
	$recent_posts = wp_get_recent_posts( $latest_post_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>';
	}

}

Default recent posts is 3 posts, you can change posts number $number = 3 or ‘numberposts’ => 10, anyway no needed to change default number, you can change ‘post_type’ => ‘post’ to ‘post_type’ => ‘page’ will be display recent pages, and you can display recent posts from post type post and post type page ‘post_type’ => array(‘post’, ‘page’) and you can display custom post type recent posts ‘post_type’ => ‘movies’ and you can display recent posts from post type post and post type page and custom post type ‘post_type’ => array(‘post’, ‘page’, ‘movies’)

Make Recent Posts Shortcode

Copy recent posts shortcode function code and paste it in your functions.php file.

/* Recent Posts Shortcode Function */
function custom_recent_posts_shortcode($atts){

	if( !empty($atts['number']) ){
		$number = $atts['number'];
	}else{
		$number = 3; // default is 3 posts
	}

	ob_start();

	?>
		<div class="recent_posts_shortcode_custom_wrap"><ul><?php custom_recent_posts($number); ?></ul></div>
	<?php

	return ob_get_clean();

}
add_shortcode('custom_recent_posts', 'custom_recent_posts_shortcode'); // your shortcode will be [custom_recent_posts number=""]

Now your shortcode will be [custom_recent_posts number=””] in number=”” enter number of recent posts, default is 3 posts, you can using [custom_recent_posts] directly without number=”” attribute, but your recent posts will be 3 posts only.

You can using custom wrap, for example:

<div class="recent_posts_shortcode_custom_wrap"><ul><?php custom_recent_posts($number); ?></ul></div>

Display Recent Posts

In your posts or pages, etc, use [custom_recent_posts number=””]

If you want to display recent post outside posts, for example in footer, open your footer.php file, and paste this code:

<ul><?php custom_recent_posts(5); ?></ul>

Now will be display 5 recent posts in footer, change number 5 to display more recent posts.

If you want to display recent posts shortcode inside Text Widget, like this:

recent posts shortcode in widget

Just add this line in your functions.php file:

add_filter('widget_text', 'do_shortcode');

Enjoy.