【问题标题】:wordpress get_categories count also custom post typewordpress get_categories 计数也自定义帖子类型
【发布时间】:2015-08-21 16:03:09
【问题描述】:

在我的主页上,我想展示每个类别有多少帖子。所以我使用 get_categories->count 。但我有一个新闻自定义帖子类型。每个新闻项目都与一个类别相关联。那么如何从计数中排除自定义帖子类型?

这是我的代码:

$args = array(
    'type'  => 'post',
    'child_of'  => 0,
    'parent'  => '',
    'orderby'  => 'name',
    'order'  => 'ASC',
    'hide_empty'  => 0,
    'hierarchical' => 1,
    'exclude' => array(1,8),
    'include' => '',
    'number' => '',
    'taxonomy'  => array('category'),
    'pad_counts' => true
  );
$categories = get_categories( $args );

然后我在循环中使用:echo $category->count

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    如果我正确理解了您的问题,这应该会对您有所帮助。以下代码将列出您的所有帖子类别及其各自的帖子计数,从计数总数中省略新闻 CPT 帖子。

    <?php $cats = get_categories();  // Get categories ?>
    
    <?php if ($cats) : ?>
        <ul>
        <?php // Loop through categories to print name and count excluding CPTs ?>
        <?php foreach ($cats as $cat) { 
    
            // Create a query for the category to determine the number of posts
            $category_id= $cat->term_id;
    
            $cat_query = new WP_Query( array( 'post_type' => 'post', 
                        'posts_per_page' => -1,
                        'cat' => $category_id
            ) );
            $count = $cat_query->found_posts;
    
            // Print each category with it's count as a list item
            echo "<li>" . $cat->name . " (" . $count . ")</li>";
    
        } ?>
    
        <?php wp_reset_query();  // Restore global post data  ?> 
        </ul>
    <?php endif; ?>
    

    【讨论】:

    • 嗨,感谢您的回答。这正是我想要的,并且有效。但是当我检查 codex 时,他们实际上建议不要使用 query_posts。有没有其他方法可以得到相同的结果? link[链接]
    • 我继续使用 wp_query() 而不是 query_posts()。一切都应该以同样的方式工作。让我知道! 〜科里
    • 我改成这样:$wp_query("cat=$category_id&posts_per_page=-1");并得到这个错误:致命错误:函数名必须是字符串
    • 那不行,你应该使用我上面发布的编辑代码。
    猜你喜欢
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 2021-12-23
    • 1970-01-01
    相关资源
    最近更新 更多