WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

Thanks in advance for any help.

share|improve this question
up vote 1 down vote accepted

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

$args = array(
  'parent' => 0,
  'hide_empty' => 0

$categories = get_categories( $args );

echo count( $categories );    
share|improve this answer
Probably want to add a hide_empty=0 to this so the unused cats are counted. Not sure you need to do an orderby if we're just counting but we basically posted the same thing. You were faster :) – Imperative Ideas Oct 10 '13 at 7:05
Thanks for the nice criticism. I edited my one and added your suggestion 'hide_empty' => 0. And also deleted the unnecessary orderby. :) – Mayeenul Islam Oct 10 '13 at 13:33
This works. Thank you! – user2655393 Oct 10 '13 at 23:00

You could do it using get_categories()

    $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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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