Retrieving taxonomy terms belonging to a set of posts

This issue comes up often, where I need to show a list of all terms belonging to a set of posts being queried. One useful case would be to allow the user to filter the queried posts by clicking on a ‘term’ from the generated list of terms.

Let’s say we are on a taxonomy-term archive page, and we want to show a list of all the terms belonging to the queried set of posts. This is what we can do:

// getting the posts we want based on the taxonomy of current query, returning an array of post IDs
$someposts = get_posts(
    array(
        'post_type' => 'custom_post_type',
        'posts_per_page' => -1,
        'fields' => 'ids', // return an array of ids
        'tax_query' => array(
            array(
                'taxonomy' => get_query_var('taxonomy'),
                'field' => 'slug',
                'terms' => $term_slug = get_queried_object()->slug,
            )
        )
    )
);

And to get all the taxonomy terms belonging to the retrieved posts above:

$somepoststerms = get_terms(
    array(
        'taxonomy' => 'custom_tax',
        'object_ids' = $someposts;
    )
);

Leave a Comment