fbpx

Here is an example of creating a shortcode with a parameter. I choose the recent post shortcode because it is the shortcode we usually use in the backend team

first thing is we have to code the post loop that will fetch all the post from the database, here is the simple example:


	// Query
	$the_query = new WP_Query( array ( 'posts_per_page' => -1 ) );
	
	// Posts
	echo '<ul>';
	while ( $the_query->have_posts() ) :
		$the_query->the_post();
		echo '<li>' . get_the_title() . '</li>';
	endwhile;
	echo '</ul>';
	
	// Reset post data
	wp_reset_postdata();

Now, since we are done in coding the structure of the loop we can now combine it to the shortcode. I put comments in the code to explain the use of each part

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

	// Attributes
	$atts = shortcode_atts( // this variable is use to declare the shortcode parameters
		array(
			'posts' => '5', //by adding the default value in the parameter the shortcode still become usable even if the user did not declare the number of post to show in the shortcode
		),
		$atts
	);

	// Query
	$the_query = new WP_Query( array ( 'posts_per_page' => $atts['posts'] ) ); // as you notice the -1 is replace with $atts['posts'] which contain the default value
	
	// 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; //it will return all the contents. 
}
add_shortcode( 'recent-posts', 'recent_posts_shortcode' );

As you notice I use return instead of using echo in each content because base on my experience using echo in the shortcode may break the layout of the page where the shortcode is used.

For example I use

<div id="parentcontainer">
[recent-posts posts="2"]
</div>

//If I use echo in shortcode this is what I see sometimes in my DOM

<ul>
<li>Sample Title 1</li>
<li>Sample Title 2</li>
<li>Sample Title 3</li>
</ul>
<div id="parentcontainer">
</div>

//as you notice the result of the shortcode is go outside the parentcontainer..

BTW..
We can now call the shortcode like this [recent-posts posts=”2″] or [recent-posts] and aside from posts parameter we can always add as many parameters as you want.