How to create a shortcode to show limited recent posts in WordPress?

Photo of author
Written By geekerhub

Lorem ipsum dolor sit amet consectetur pulvinar ligula augue quis venenatis. 

Shortcodes in WordPress are codes that allow you to do various things with little effort. It allow the administrator to execute code inside WordPress posts, pages, and widgets without writing any code directly.

Shortcode with the name ‘recent-posts’ created and you can reuse anywhere in your posts, pages and widgets. To use this shortcode you need to pass one attribute along with the shortcode name. If you don’t use posts arguments, it will show 5 recent post by default.

[recent-posts posts='10']

You need to put below code snippet in your theme’s functions.php file.

// Add Shortcode
function recent_posts_shortcode( $atts , $content = null ) {

	// Attributes
	$atts = shortcode_atts(
		array(
			'posts' => '5',
		),
		$atts,
		'recent-posts'
	);

	// Query
	$the_query = new WP_Query( array ( 'posts_per_page' => $atts['posts'] ) );
	
	// Posts
	$output = '<ul>';
	while ( $the_query->have_posts() ) :
		$the_query->the_post();
		$output .= '<li>' . get_the_title() . '</li>';
	endwhile;
	$output .= '</ul>';
	
	// Reset post data
	wp_reset_postdata();
	
	// Return code
	return $output;

}
add_shortcode( 'recent-posts', 'recent_posts_shortcode' );

Leave a Comment