Counting Categories in Wordpress

Sometimes I forget that Wordpress is php and mysql. So when I look at it I tend to forget that to do somethings al it takes is clean code and if there is no function that does what you want you will have to write it yourself.

Same with the count categories. What I plan to do with it is display it in a way like at the demo layout but of course I need to know how many categories there are.

Code for it came from a plugin at http://jonas.rabbe.com/ and I stipped the part that displays it to use futher in a variable

$request = “SELECT COUNT(DISTINCT cat_ID) FROM $wpdb->categories, $wpdb->post2cat, $wpdb->posts WHERE post_status = ‘publish’ AND ID = post_id AND category_id = cat_ID;”;
//    if (!$all_posts) $request .= ” AND comment_post_ID=$id”;
$num = $wpdb->get_var($request);

It selects only the categories with posts n it so that is good as I do not want categories displayed that are empty.

Next is a piece of code I wrote years ago on a site that pulled info from a db and putted it in a table. That table had 3 rows and the code kept counting if it hit 3 to start a new line. I wil have to look it up where I have it and modify it a bit

Leave a Reply