3

I'm trying to get a count of the categories that are subcategories of a category with the id $categoryId.

In the documentation for the term query object, which is the primary argument to get_terms, the count parameter is listed, with the description:

(bool) Whether to return a term count (true) or array of term objects (false). Will take precedence over $fields if true. Default false.

Based off of this, I think the following code should return an integer term count. However, it does not, it returns an array of term objects, the same as if I didn't include the count argument. I've tried this with the values 1, "true", "True" and True as well.

get_terms(
    array(
        'parent' => $categoryId,
        'taxonomy' => 'category',
        'count' => true
    )
);

After searching more, I found this code, which works:

wp_count_terms( 'category', array( 'parent' => $categoryId ) );

Why does the count argument have no effect in this situation? Is this behavior consistent?

0

Not sure from which version, but count argument not used anymore. Just checked WP_Term_Query class and found nothing related to count argument in get_terms() method, but you can still find it in constructor of this class. To return terms count only, you need to set count for fields argument.

get_terms(
    array(
        'parent' => $categoryId,
        'taxonomy' => 'category',
        'fields' => 'count'
    )
);

The function wp_count_terms() just do the same.

function wp_count_terms( $taxonomy, $args = array() ) {
    $defaults = array('hide_empty' => false);
    $args = wp_parse_args($args, $defaults);

    if ( isset($args['ignore_empty']) ) {
        $args['hide_empty'] = $args['ignore_empty'];
        unset($args['ignore_empty']);
    }

    //HERE IT SETS COUNT VALUE FOR YOU
    $args['fields'] = 'count';

    return get_terms($taxonomy, $args);
}

It's not the first time I noticed, that english version of codex is outdated. For example spanish codex don't have a 'count' argument - https://codex.wordpress.org/es:Function_Reference/get_terms

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.