繁体   English   中英

wordpress get_categories还可以统计自定义帖子类型

[英]wordpress get_categories count also custom post type

在我的主页上,我想显示每个类别有多少帖子。 所以我使用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

如果我正确理解了您的问题,这应该会对您有所帮助。 以下代码将列出您的所有帖子类别及其各自的帖子数,从总数中删除新闻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; ?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM