Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save carlaizumibamford/4b4f391f3ac7cc304a263847940deccd to your computer and use it in GitHub Desktop.
Save carlaizumibamford/4b4f391f3ac7cc304a263847940deccd to your computer and use it in GitHub Desktop.
Simple Taxonomy Query:
Display posts tagged with bob, under people custom taxonomy:
$args = array(
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'people',
'field' => 'slug',
'terms' => 'bob',
),
),
);
$query = new WP_Query( $args );
Multiple Taxonomy Handling:
Display posts from several custom taxonomies:
$args = array(
'post_type' => 'post',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'movie_genre',
'field' => 'slug',
'terms' => array( 'action', 'comedy' ),
),
array(
'taxonomy' => 'actor',
'field' => 'term_id',
'terms' => array( 103, 115, 206 ),
'operator' => 'NOT IN',
),
),
);
$query = new WP_Query( $args );
Display posts that are in the quotes category OR have the quote post format:
$args = array(
'post_type' => 'post',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'quotes' ),
),
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array( 'post-format-quote' ),
),
),
);
$query = new WP_Query( $args );
Nested Taxonomy Handling:
The 'tax_query' clauses can be nested, to create more complex queries. Example: Display posts that are in the quotes category OR both have the quote post format AND are in the wisdom category:
$args = array(
'post_type' => 'post',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'quotes' ),
),
array(
'relation' => 'AND',
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array( 'post-format-quote' ),
),
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'wisdom' ),
),
),
),
);
$query = new WP_Query( $args );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment