1

I want to query/list all the terms (from all the custom taxonomies) within a custom post type with their custom post count. This is what I have so far...

$the_query = new WP_Query( array(
    'post_type' => 'teacher',
    'tax_query' => array(
        array(
            'taxonomy' => 'ALL CUSTOM TAXONOMIES',
            'field' => 'id',
            'terms' => 'ALL TERMS'
        )
    )
) );
$count = $the_query->found_posts;
$term_name = $the_query->get_term;
echo $term_name;
echo ' - ';
echo $count;
1

If the taxonomies in question are used ONLY in the post_type in question, then the following simple function will do what you need:

function
count_term_use ($post_type)
{
    $args = array (
        'taxonomy' => get_object_taxonomies ($post_type, 'names'),
        ) ;
    foreach (get_terms ($args) as $term) {
        echo "$term->name - $term->count\n" ;
        }

    return ;
}

However, if a taxonomy is shared by multiple post_type's then the above counts will reflect the total number of posts of any type that use the term, which is not what you're looking for. If that is true in your case, let me know and I'll post the more complicated (and expensive in terms of execution time/db queries) code.

  • I assume I put this in my theme file, in which case it doesn't display anything? – Pete Feb 17 '17 at 19:47
  • I'll even settle for all the terms from a custom taxonomy and their count. – Pete Feb 17 '17 at 19:51
  • 1
    yes, you can put in functions.php. you then have to call the function in some theme template, e.g., count_term_use('teacher') – Paul 'Sparrow Hawk' Biron Feb 17 '17 at 21:05
0

There is the built-in function to count the posts – wp_count_posts(). You can use it to count any post type and any post status:

$published = wp_count_posts('teacher')->publish;
$future = wp_count_posts('page')->future;

For more see wp_count_posts() in the Code Reference.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.