Filtering a custom post type by custom taxonomy in archive template

Let say you have “book” post type and “genre” taxonomy.
And you want to get books with genre of “scifi”.

You can pass the parameter in the url using:

?taxonomy=genre&term=scifi

Then you can get those parameter using get_query_var('taxonomy') and get_query_var('term') and add them to the WP_Query arguments.

$taxonomy = get_query_var('taxonomy');
$term = get_query_var('term');

$args = array(
    'post_type' => 'book',
    'tax_query' => array(
        array(
            'field'    => 'slug',
            'taxonomy' => $taxonomy,
            'terms'    => $term,
        )
    ),
);
$query = new WP_Query($args);

Leave a Comment