WordPress: Querying multiple post types, limiting by individual taxonomies

Apr
8

No Comments - LEAVE A COMMENT

Today I had a case where I needed to create a list of posts from two different post types, which in itself isn’t all that hard using WP_Query(). The catch here was I needed all posts from one post type and just the posts that were in a certain taxonomy from the other. The solution was a simple tax_query() using a relation of “or” and using the “IN” operator to isolate the posts we wanted. This may or may not be the best solution, but it’s the one that worked for us, so I thought I’d share!

For the record, these are the arguments sent through a WP_Query(). If you are not experience with it check it out on the codex. Tons of goodies there!

View as a pastebin


$args = array(
  'post_type' => array('post_type_one', 'post_type_two'), //our two post types
  'tax_query' => array(
  'relation' => 'OR', 
      array(
       'taxonomy' => 'tax_name_one', //name of taxonomy where we 
   only want to look for posts in one taxonomy. 
		'field' => 'slug', //can use slug, or ID. slug is 
   easier here as we know they are not going to change.
       'terms' => array( 'specific_term' ), // the specific slug of the term we are looking for
       'operator' => 'IN', // the posts must be in this term 
      ), 
      array(
       'taxonomy' => 'tax_name_two', //name of second taxonomy 
   where we want to show all items
       'field' => 'slug',
       'terms' => array( 'event', 'in-the-news', 'newsletter', 
'press-release', 'staff-presentation' ), //all the terms from 
the second taxonomy
       'operator' => 'IN',
      ),
    ),
  'order' => 'DESC',
  'posts_per_page' => 10
);

Jump to Comments

Leave a Reply

Your email address will not be published. Required fields are marked *