Query posts by a custom taxonomy term in WordPress
Categories and tags are the built-in taxonomies, but most projects also register their own: genre, location, brand. Sooner or later you need all posts of one term: portfolio items of one project type, products of one brand, the latest articles in a genre. The tool for it is WP_Query with the tax_query parameter.
Problem: Get all posts that belong to a specific term of a custom taxonomy.
Solution: A WP_Query with a tax_query condition, matched by the term slug.
The query
In a template:
<?php
$query = new WP_Query( array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 10,
'tax_query' => array(
array(
'taxonomy' => 'genre',
'field' => 'slug',
'terms' => 'thriller',
),
),
) );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
the_title( '<h2><a href="' . esc_url( get_permalink() ) . '">', '</a></h2>' );
}
wp_reset_postdata();
}
The term can be matched by term_id, slug or name. The slug is usually the safest choice: IDs differ between the local copy and the live site.
wp_reset_postdata() after the loop restores the global $post. Without it, the_title() and get_the_ID() further down the page return the last post of this loop.
Several terms and several taxonomies
terms accepts an array, and operator sets how they are combined (IN by default, also AND and NOT IN). Several conditions are joined with relation:
<?php
$args['tax_query'] = array(
'relation' => 'AND',
array(
'taxonomy' => 'genre',
'field' => 'slug',
'terms' => array( 'thriller', 'crime' ), // either of them
),
array(
'taxonomy' => 'location',
'field' => 'slug',
'terms' => array( 'london' ),
'operator' => 'NOT IN',
),
);
For hierarchical taxonomies, posts of the child terms are included by default. Add 'include_children' => false to get only the posts assigned to the term itself.
NOTE: If the list is the term archive itself (/genre/thriller/), you do not need a custom query: WordPress already queries those posts for taxonomy-genre.php. Change its parameters with pre_get_posts, otherwise the pagination of the archive will not match your loop.