3

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.

2 Answers 2

4

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
  • 1
    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 :) Commented Oct 10, 2013 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. :) Commented Oct 10, 2013 at 13:33
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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