1

I have a custom post type "Services". It has a hierarchal taxonomy of "service-category". Service-category has both parent and child terms.

I need to count the number of parent terms in the taxonomy. NOT posts. The # of terms in the taxonomy is being used in my code to layout the page in a recursive loop.

Everything I have researched is about the number of posts per term, not the number of terms in the taxonomy.. I am sure I am missing an obvious way of doing this, but I haven't run across it.

Thanks in advance for your help!

4

As @shanebp suggests, you could use wp_count_terms() like this:

$numTerms = wp_count_terms( 'service-category', array(
    'hide_empty'=> false,
    'parent'    => 0
) );

The above will list All top parent terms, empty or not. This function uses get_terms() functions arguments which can be found in the link or the arguments below:

$args = array(
    'orderby'           => 'name', 
    'order'             => 'ASC',
    'hide_empty'        => true, 
    'exclude'           => array(), 
    'exclude_tree'      => array(), 
    'include'           => array(),
    'number'            => '', 
    'fields'            => 'all', 
    'slug'              => '', 
    'parent'            => '',
    'hierarchical'      => true, 
    'child_of'          => 0, 
    'get'               => '', 
    'name__like'        => '',
    'description__like' => '',
    'pad_counts'        => false, 
    'offset'            => '', 
    'search'            => '', 
    'cache_domain'      => 'core'
); 
  • 1
    I made two edits to your code and then it works. Missing a comma between 'service-category' and array. Added 'parent'=>0 to limit the count to parent terms only. Without this the count also included the child terms and I only want parents. I will mark your answer as correct. Thanks so much! – BitBug Dec 11 '14 at 22:14
0

Try this. Untested but should work -- get_the_terms returns an array with each term, and then sizeof() counts it, returning an integer. The variable $number will return an integer corresponding to the number of terms.

$terms = get_the_terms ( $post->ID, 'service-category' );
$number = sizeof ($terms);
echo $number;

if ( $number == XX ) {
// do something
}
  • That is only returning the number 1. I also tried changing 'sizeof' to 'count' with the same result. Also tried using get_terms instead of get_the_terms. No joy. – BitBug Dec 11 '14 at 21:49
  • Hmmm. Just tested on my end and it works. Maybe you should double check the taxonomy name. – edwardr Dec 11 '14 at 21:58
  • @EdwardR.Jenkins your code checks the terms for the given post, not every term of the taxonomy. – tfrommen Dec 11 '14 at 21:59
  • Ah, I misunderstood the original question. Sorry. – edwardr Dec 11 '14 at 22:00

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.