The other day, I wrote about modifying the default WordPress loop to exclude specific post formats. Today, I’ll be talking about pretty much the opposite and setting up a loop that retrieves posts of a specific post type.
This is the code I used in the theme’s
global $post; $tmp_post = $post; $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'order' => 'DESC', 'tax_query' => array( array( 'taxonomy' => 'post_format', 'field' => 'slug', 'terms' => array( 'post-format-aside' ) ) ) ); $sidebar_posts = get_posts( $args ); foreach ($sidebar_posts as $post ) : setup_postdata( $post ); // Output post here endforeach; $post = $tmp_post;
So, what’s going on here? In short, we’re using the
get_posts function with a
tax_query variable to create a second loop that only retrieves posts of a specific post type.
The first thing I do is reference the global WordPress
post object, and then I store a reference to it’s current value. Technically, I don’t need to do this, but I don’t like modifying globals.
The next thing is to set up the query arguments. I want all published posts in descending order and (here’s the only “tricky” part, the
tax_query syntax) of the type
Then it’s simply a matter of passing these arguments to
get_posts and looping through and outputting the results. Once I’m finished, I restore the global
post variable to its original value.