【问题标题】:How to display number of posts in wordpress category including subcategories?如何显示包含子类别的 wordpress 类别中的帖子数量?
【发布时间】:2016-03-24 19:04:06
【问题描述】:

在列出类别时,我想显示有多少帖子,包括子类别。我试过这个:

$cat_parent_ID = isset( $cat_id->category_parent ) ? $cat_id->category_parent : '';

            if ($cat_parent_ID == 0) {

                $tag = $cat_id;

            } else {

                $tag = $cat_parent_ID;

            }
$q = new WP_Query( array(
                    'nopaging' => true,
                    'tax_query' => array(
                        array(
                            'taxonomy' => 'category',
                            'field' => 'id',
                            'terms' => $tag,
                            'include_children' => true,
                        ),
                    ),
                    'fields' => 'ids',
                ) );
                $allPosts = $q->post_count;

                echo $allPosts;
            ?>

            <?php _e( 'posts found', 'agrg' ); ?>

如果类别没有孩子,上述工作正常。但是,如果我单击具有子类别的类别,即使有帖子,我也会看到 0 posts found,但它们都在子类别中(因此父类别中有 0 个帖子,但子类别中有一些帖子)

我哪里出错了,我应该改变什么?

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    尝试使用此功能:

    function wp_get_cat_postcount($id) {
        $cat = get_category($id);
        $count = (int) $cat->count;
        $taxonomy = 'category';
        $args = array(
            'child_of' => $id,
        );
        $tax_terms = get_terms($taxonomy,$args);
        foreach ($tax_terms as $tax_term) {
            $count +=$tax_term->count;
        }
    
        return $count;
    }
    

    此函数将返回指定类别及其子类别(如果有)的帖子总数,只需传递类别 ID。 我希望它对你有用,谢谢..

    【讨论】:

    • 如果一个帖子被分配到多个子类别,它会被多次计算,所以你使用这个函数会得到错误的结果
    • 如果帖子属于多个类别或同时选择了父项和子项,则结果错误。
    【解决方案2】:
    function wt_get_category_count($input = '') {
    global $wpdb;
    if($input == '')
    {
        $category = get_the_category();
        return $category[0]->category_count;
    }
    elseif(is_numeric($input))
    {
        $SQL = "SELECT $wpdb->term_taxonomy.count FROM $wpdb->terms, $wpdb->term_taxonomy WHERE $wpdb->terms.term_id=$wpdb->term_taxonomy.term_id AND $wpdb->term_taxonomy.term_id=$input";
        return $wpdb->get_var($SQL);
    }
    else
    {
        $SQL = "SELECT $wpdb->term_taxonomy.count FROM $wpdb->terms, $wpdb->term_taxonomy WHERE $wpdb->terms.term_id=$wpdb->term_taxonomy.term_id AND $wpdb->terms.slug='$input'";
        return $wpdb->get_var($SQL);
    }
    }
    

    您可以通过

    在您的 HTML 文件中回显此内容
    <p><?php echo wt_get_category_count();?></p>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多