0

I want to list all custom taxonomy terms related to another taxonomy.

For example the following case:

Custom Post Type: Car

Taxonomy 1: Brand

->Terms: Audi, Bentley, BMW, Bugatti, ...

Taxonomy 2: Type

->Terms: Compact, Electro, Hybrid, SUV, ...

Here, I would like to list all "Types" (with count in brackets) that are related to the post type "Car" and have the brands term "BMW", sorted by count.

Result should be something like this:

<li>Compact (6)</li>
<li>SUV (4)</li>
<li>Electro (2)</li>

I have done a lot of research and found this solution:

$brands_slug = get_query_var('term');   
$brands_post_ids = get_posts(array(
  'post_type' => 'car',
  'posts_per_page' => -1,
  'tax_query' => array(
    array(
      'taxonomy' => 'brand',
      'field'    => 'slug',
      'terms'    => $brands_slug
    )
  ),
  'fields' => 'ids'
));

$args = array(
  'orderby' => 'count',
  'order' => 'DESC'
);

$types = wp_get_object_terms($brands_post_ids, 'type', $args);

foreach ($types as $type) { 
  echo "<li>$type->name ($type->count)</li>";
}

It works quite well already, but the count is not relative to passed IDs. It is the global count of all posts assigned to these terms.

Can anybody help me with that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.