How do I count how many top level categories there are?

I need to calculate some dynamic CSS based on how many top level categories exist. (NOT how many posts are in a category, or how many categories a post belongs to… Nothing about posts at all, just how many top level categories there are)

I am new to PHP, but I couldn’t find any WP functions that would return the number I’m looking for.

Read More

Thanks in advance for any help.

Related posts

2 comments

  1. As the Codex says, this is the code block to query for only the Top Level categories — the parents. With this, I used the PHP function count().

    <?php    
    $args = array(
      'parent' => 0,
      'hide_empty' => 0
      );
    
    $categories = get_categories( $args );
    
    echo count( $categories );    
    ?>
    
  2. You could do it using get_categories()

    <?php
        $categories = get_categories('hide_empty=0');
        echo count($categories);
    ?>
    

    Wrap it in a function and return the value instead of echoing it if you need to store it for use in another part of your code.

    Edit – I see another version of this was posted already. Either one should work. Mayeenul Islam’s was probably a bit more elegant since he uses the count function (which I should have done… and now have). They’re basically the same thing.

Comments are closed.