• Resolved ankurt

    (@ankurt)


    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

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter ankurt

    (@ankurt)

    Ok, guys, turns out getting the post count by counting the number of posts beloning to the category is not the way to go. Here’s the working code:

    global $post;
    $categories = get_categories();
    foreach ( $categories as $c ) {
    	$counts[$c->term_id] = $c->count;
    }

    That gives you a $counts array populated with category id and count number, which you can asort, reverse and slice.

    Does anyone know why counting the number of posts beloning to a category doesn’t give you a proper category count?

    Thread Starter ankurt

    (@ankurt)

    He he, figured it out. get_posts defaults to showing 5 posts, that’s why!!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Please help me with my "popular categories" code’ is closed to new replies.