WordPress.org

Forums

[resolved] Should be Easy: know how much posts there are inside a category (7 posts)

  1. ELAN42.com
    Member
    Posted 5 years ago #

    Hi.

    I'm trying to surpass the page-category chaos of WordPress, using only categories.
    To do this I just need to display a category with only one post, as a page.

    How can I know, inside or before the loop, how much posts there are inside a category?

  2. ELAN42.com
    Member
    Posted 5 years ago #

    This works but it's not recursive:
    (int) get_category($CATEGORY_ID)->category_count;

  3. Mark / t31os
    Moderator
    Posted 5 years ago #

    <?php
    $category_posts = get_term('56','category');
    echo $category_posts->count;
    unset($category_posts);
    ?>

    Update 56 to the ID for your category.

    Hope that helps... :)

  4. ELAN42.com
    Member
    Posted 5 years ago #

    Thank you t31os_

    This is for sure cleaner code, but it's not counting the posts in the sub-categories of that category.

    How can I do?

  5. Mark / t31os
    Moderator
    Posted 5 years ago #

    Sub-category posts aren't part of the count for posts in the parent..

    However being that i'm a nice guy...

    <?php
    $catid = '56';
    $category_posts = get_term($catid,'category');
    $subcatposts = get_terms('category', 'parent='.$catid);
    
    $post_count = $category_posts->count;
    unset($category_posts);
    
    foreach($subcatposts as $subcat) {
    	$post_count = $post_count + $subcat->count;
    }
    unset($subcatposts);
    echo $post_count;
    ?>

    There's no error checking in that code, as in the foreach loop is expecting results, if it doesn't have any you'll get errors..

    Code works though!... :)

  6. ELAN42.com
    Member
    Posted 5 years ago #

    Thank you very much kitty !!!

    Now I don't need pages anymore ...

  7. Mark / t31os
    Moderator
    Posted 5 years ago #

    Happy to help... :)

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.