Wordpress 显示自定义帖子类型的帖子计数

问题描述 投票:0回答:1

我创建了一个自定义帖子类型和一个带有 CPT 插件的分类法。我使用 Elementor 创建了一个存档页面来显示创建的分类中的帖子。

我想要一个短代码来动态显示每个分类的帖子数量。

例如,我有帖子类型的 AI-Tools,其分类为 best-ai-tools,该分类下有 30 多个类别。

谢谢你

wordpress custom-post-type elementor
1个回答
0
投票

这是我为我的一位客户使用的简码:


function category_product_count_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'id' => '',
    ), $atts );

    $category = get_term( $atts['id'], 'product_cat' );
    $args = array(
        'post_type' => 'product',
        'posts_per_page' => -1,
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field' => 'term_id',
                'terms' => $category->term_id,
            ),
        ),
    );
    $query = new WP_Query( $args );
    $count = $query->post_count;
    
    return $count
    
}
add_shortcode( 'category_product_count', 'category_product_count_shortcode' );

最终使用的简码是这样的:

[category_product_count id="12"]

它返回产品类别下的产品数量。您可以根据您的需要和您的 CPT 或分类标准等修改此代码。

© www.soinside.com 2019 - 2024. All rights reserved.