Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
add comment

2 Answers

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().

<?php    
$args = array(
  'parent' => 0,
  'hide_empty' => 0
  );

$categories = get_categories( $args );

echo count( $categories );    
?>
share|improve this answer
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 :) –  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
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

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.