4

I want to display the count of a Custom Taxonomy based on a specific Custom Post Type. At the moment, I'm using get_terms to list all terms of the Taxonomy. The Taxonomy is used by more than one Post Type. So the counter shows all the usage of the Taxonomy for every Post Type.

Is there a way to limit the count on a single Post Type?

Here is my actual code:

get_terms(array(
    'taxonomy'      => 'tax',
    'hide_empty'    => true,
    'orderby'       => 'count',
    'order'         => 'DESC',
    'number'        => '10',
));

Inside the foreach, I'm using term->count to show the usage counter.

Cray
  • 3,872
  • 7
  • 36
  • 96

2 Answers2

4

I wouldn't recommend using get_terms because this returns all terms of a taxonomy and not all terms associated with posts.

The alternative solution is to use get_posts, read more here https://developer.wordpress.org/reference/functions/get_posts/

$my_posts = get_posts(array(
  'post_type' => 'post', //post type
  'numberposts' => -1,
  'tax_query' => array(
    array(
      'taxonomy' => 'tax', //taxonomy name
      'field' => 'id', //field to get
      'terms' => 1, //term id
    )
  )
));

Then you can count the number of posts returned:

$count = count($my_posts);
designtocode
  • 2,019
  • 4
  • 15
  • 30
2

I think following link are more helpful to better understanding. Link

And this is code serve for you.

$args = array(
    'post_type'      => 'Your_custom_post_type',//Your custom post type here.
    'tax_query'      => array(
        array(
            'taxonomy' => 'Your_taxonomy',//Your taxonomy is here.
            'field' => 'slug',
        )
    )
);

Now we print_r the $args for the better understanding exactly what we get.

_e('<pre>');
print_r($args);
_e('</pre>');

Just get your query

$your_query = new WP_Query( $args );
Dhruv
  • 614
  • 5
  • 14