Being able to display a list of posts within a page (or other post) is very useful. In this tutorial I’m going to show you how to write a simple post query short code that will allow you to display a list of posts from any category, tag, or custom taxonomy.


I apologize if I move a little quickly in the video, I was limited for time.

Our final code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function pippin_show_posts_shortcode($atts, $content = null ) {
 
	extract( shortcode_atts( 
		array(
    		'tax' => 'category',
			'terms' => ''
    	), $atts ) 
	);
 
	if($terms) {
		if(strpos($terms, ',')) {
			$terms = explode(',', $terms);
		}
	}
 
	$tax_query = array(
		array(
			'taxonomy' => $tax,
			'terms' => $terms,
			'field' => 'slug'
		)
	);
 
	$display = '
    ‘; $post_args = array(‘tax_query’ => $tax_query, ); $posts = get_posts($post_args); if($posts) { foreach ($posts as $p) { $display .= ‘

  • ‘ . get_the_title($p->ID) . ‘
  • ‘; } } else { $display .= ‘

  • No posts found
  • ‘; } $display .= ‘

1
2
3
4
5
';
 
	return $display;
}
add_shortcode('query_posts', 'pippin_show_posts_shortcode');
Download
  1. guvner

    Thanks for this Pippin – just what I needed.

    I found that the plugin defaults to displaying just 5 posts so for anyone who wants to show more, just edit line 37 and include the numberposts argument as follows:

    $post_args = array('tax_query' => $tax_query, 'numberposts' => 10, );

    Mike 🙂

  2. dave

    Excellent thank you Pippin, your post has helped me to sole a problem thats has been bugging me for the last 2 hours, the internet is great…thank you!

  3. Keith Williams

    Works great for the category of a post but I can’t figure out how to display custom posts with using their custom taxonomy. Any ideas?

    • Pippin

      In the short code, set tax=”NAME OF YOUR TAXONOMY”

Comments are closed.