How do I get all taxonomies a post is related to – WordPress

Thanks for taking the time to look at this question and hopefully you can help!

I’m looking to run a wordpress query which retrieves all taxonomies related to another.

Read More

For example; say I have a category/taxonomy of products and a category/taxonomy of sub products in my WordPress site. When I land on a product category/taxonomy page, I would like to see a list of all the related sub categories/taxonomies.

I hope this makes sense as after many hours spent googling, all I can find are questions asking how to get all posts related to a taxonomy – not the other way round!

Many thanks in advance!

Patrick

Related posts

Leave a Reply

1 comment

  1. If I understand the question, you would like to get the taxonomies and terms that apply to the products listed on a particular page, e.g. a category or taxonomy page.

    Suppose that you have an array of product IDs $product_id, for example the IDs of products currently being displayed. You should be able to get the taxonomies and terms that apply to those products as follows:

    global $wpdb;
    
    $ids = implode(',', $product_id);
    $query = "SELECT x.taxonomy, t.name FROM wp_term_taxonomy AS x
              JOIN wp_term AS t on t.term_id = x.term_id
              JOIN wp_terms_relationships AS r on r.term_taxonomy_id = x.term_taxonomy_id
              WHERE r.object_id IN ($ids)
              GROUP BY x.taxonomy, t.name";
    $taxonomies = $wpdb->get_results( $query );
    

    In the above:

    SELECT x.taxonomy, t.name FROM wp_term_taxonomy AS x
    

    is the base table of taxonomies (names) and the term_ids of their terms.

    JOIN wp_terms AS t on t.term_id = x.term_id
    

    matches each of the term_ids from wp_term_taxonomy with its term name.

    JOIN wp_term_relationships AS r on r.term_taxonomy_id = x.term_taxonomy_id
    

    then matches that with entries in wp_term_relationships which shows which products (custom post IDs) use those terms.

    WHERE r.object_id IN ($ids)
    

    limits the list to only those terms relevant for the products in your list.

    Since, in this example, we are asking for x.taxonomy and t.name,

    GROUP BY x.taxonomy, t.name
    

    makes sure that you don’t have duplicates. You could get additional fields if you needed by changing the SELECT.

    So, once you run get_results(), you should have an array of objects, each with a taxonomy name and term name. The general scheme will be:

    +-----------+-------+
    | taxonomy1 | term1 |
    +-----------+-------+
    | taxonomy1 | term2 |
    +-----------+-------+
    | taxonomy1 | term1 |
    +-----------+-------+
    | taxonomy2 | term1 |
    +-----------+-------+
    | taxonomy3 | term1 |
    +-----------+-------+
    ...
    

    You can now use this to create a way for visitors to select a further subset, e.g. by creating a dropdown of terms for each taxonomy.