Using a shortcode for displaying posts from inside a post



Sometimes we want to include a list of links to other posts, just inside the article text. While it’s always possible to do it manually, it could be useful to do it in a more sistematic and rich way, for example by selecting posts with a specific tag, or by displaying a styled list that includes a thumbnail and/or other information.

In order to do this, we can create a shortcode linked to a function that queries the database and displays the posts in this customized way.

First, we can create the shortcode by including the following lines in the functions.php template:

add_shortcode( 'list_posts', 'list_posts' );

function list_posts( $atts ) 
{
  // Attributes
  $defaul_atts=array();
  extract( shortcode_atts($defaul_atts, $atts)); 
  $code = 'something';
  return $code;
}

Note: to generate the basis of the above code, you can also use the useful Shortcodes Generator tool.

 

This means that we can insert a shortcode like

and the resulting variable will be: $atts = array ('tag'=>'mytag', 'showposts'=>'5')

 

Since we need to make a custom query using the WP_Query class, we can directly use the arguments of the shortcode for the custom query.

$query=new WP_Query( $atts );

$code.='';

while ( $query->have_posts() ) 
{
  $query->the_post();
  $code.='<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
} 

wp_reset_postdata();

return $code;

Another benefit is that we can also pass additional custom parameters, and this won’t affect the query result.

For instance, we can set a title, or define a specific layout for displaying the posts.

See Also:

And add some simple code to manage these custom parameters:

if(isset($atts['title']))
{
  $code.="<h3>".$atts['title'].'</h3>';
}

while ( $query->have_posts() ) 
{
  $query->the_post();

  if(isset($atts['layout']) && $atts['layout']=='simple_list')
  {
    $code.='<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>'; 
  }
  else
  {
    //something else
  }
} wp_reset_postdata();
return $code;

 

Leave a comment