Please help me with my "popular categories" code
-
Hi guys,
I wrote a function that retrieves “popular categories” and puts them inside an array. Popularity is determined by the number of posts the category has. For example, a category with 10 posts is deemed to be more popular than a category with only 3 posts. And so on. Here is the code:
global $post; $categories = get_categories(); foreach ( $categories as $c ) { $args = array ( 'category__in' => array ( $c->term_id ) ); $posts = get_posts ( $args ); $post_counts[$c->term_id] = count($posts); }
This code gets all the caregories, and for each one, does a get_posts call to get the number of posts *in that category. Then, we put our results in an assoc. array, something like $post_counts[category_id] = post_count. The rest (which I haven’t bothered to write down here because it’s pretty simple) is just doing an asort and slicing the last 5 elements of the array to get the most popular category IDs, which you can use to display posts, &c.
My problem is with the count($posts). For some reason, it counts the posts alright for the categories that have less than 5 posts. BUT, for categories that have more than 5 posts, my code simply puts the number “5”. So, most of my fields in the array are like $post_counts[33] = 5; Where 33 is category id and the post count is mysterously stuck at 5. Does anyone know how to solve this issue?
* is also tried category__and, cat, category and category__in
- The topic ‘Please help me with my "popular categories" code’ is closed to new replies.