Filtering a custom post type by custom taxonomy in archive template

I’ve seen this question posted in different forms before, but most of those solutions are centered around the admin interface, and I haven’t found any answers that apply to the front end.

I’ve got a custom post type, and an associated custom taxonomy. I’m using the archive page (archive-{custom_type}.php) to display the items, and using wp_list_categories to show a list of the custom taxonomy terms. I can manually alter the posts displayed by adding a tax_query parameter to the WP_Query call, but the problem I’m running into is I cannot figure out how to alter the taxonomy links so they point to this archive page so I can filter dynamically. I’d rather not duplicate this template’s markup and code in a taxonomy-{custom_type}.php file.

Do I need to just output the taxonomy links manually? How should the URL be structured so I can get the query param? I have query_var => true set and a rewrite rule on the custom taxonomy definition, but haven’t been able to get get_query_var() to return anything.

The end result should be a template that can list all items in the custom post type, or filter those items by their associated custom taxonomy.

2 s
2

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