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.
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
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:
In the above:
is the base table of taxonomies (names) and the term_ids of their terms.
matches each of the term_ids from wp_term_taxonomy with its term name.
then matches that with entries in wp_term_relationships which shows which products (custom post IDs) use those terms.
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,
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:
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.