最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

categories - Count how many posts in category

programmeradmin1浏览0评论

This is what I'm trying to do:

if number of posts is greater than 20 -> display link to another page (which shows all posts) if number of posts is less than 20 -> don't display the link

So far I've been able to return the number of posts using

$count_posts = wp_count_posts('inventory');
$published_posts = $count_posts->publish;

but I don't know where to go from here, any suggestions?

This is what I'm trying to do:

if number of posts is greater than 20 -> display link to another page (which shows all posts) if number of posts is less than 20 -> don't display the link

So far I've been able to return the number of posts using

$count_posts = wp_count_posts('inventory');
$published_posts = $count_posts->publish;

but I don't know where to go from here, any suggestions?

Share Improve this question edited Jul 19, 2017 at 16:26 kero 6,3401 gold badge25 silver badges34 bronze badges asked Jun 24, 2011 at 18:22 maikunarimaikunari 1652 gold badges7 silver badges14 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 20

If I remember right count of posts in category is stored persistently in category object. So use get_category() or variation of it and fetch the number out of object.

Example code (not tested):

$category = get_category($id);
$count = $category->category_count;

if( $count > $something ) {

    // stuff
} 

You can access that from the object itself:

foreach ( get_the_terms( get_the_ID(), 'taxonomy' ) as $term )
{
    printf( '%s (%s)', $term->name, $term->count );
}

another simple way to do this is using get_terms. I use this when I need to display a category list AND I need to ignore a category which has a set minimum number of posts.

 $cats = get_terms('category');
 foreach($cats as $cat){
     if($cat->count > 15){
     //do something here eg. display category name       
     //echo 'catname : ' .$cat->name;
     }
 }
发布评论

评论列表(0)

  1. 暂无评论