You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在自定义分类查询中仅统计WooCommerce有库存产品数量

WooCommerce分类统计仅包含有库存产品数量的解决方案

默认通过get_categories获取的分类计数会包含所有关联产品,包括缺货状态的。要实现仅统计有库存产品数量且不影响店铺页面产品展示,你可以通过自定义查询替换默认的计数逻辑:

修改后的完整代码

// 辅助函数:根据分类ID获取有库存的产品数量
function get_instock_product_count_for_cat( $cat_id ) {
    $args = array(
        'post_type' => 'product',
        'posts_per_page' => -1,
        'post_status' => 'publish',
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field' => 'term_id',
                'terms' => $cat_id,
                'include_children' => true, // 是否包含子分类产品,根据需求调整
            )
        ),
        'meta_query' => array(
            array(
                'key' => '_stock_status',
                'value' => 'instock',
                'compare' => '='
            ),
            // 若需要同时确保库存数量大于0,可添加以下条件
            // array(
            //     'key' => '_stock',
            //     'value' => 0,
            //     'type' => 'numeric',
            //     'compare' => '>'
            // )
        )
    );

    $products = new WP_Query( $args );
    return $products->found_posts;
}

// 短代码函数
function newcats_shortcode() {
    ob_start(); // 使用输出缓冲避免直接echo导致的内容位置错乱

    $taxonomy     = 'product_cat';
    $orderby      = 'name';  
    $show_count   = 1;      
    $pad_counts   = 1;      
    $hierarchical = 1;      
    $title        = '';  
    $empty        = 0;

    $args = array(
        'taxonomy'     => $taxonomy,
        'orderby'      => $orderby,
        'show_count'   => $show_count,
        'pad_counts'   => $pad_counts,
        'hierarchical' => $hierarchical,
        'title_li'     => $title,
        'hide_empty'   => $empty
    );

    $all_categories = get_categories( $args );
    foreach ($all_categories as $cat) {
        if($cat->category_parent == 0) {
            $category_id = $cat->term_id;
            // 调用辅助函数获取有库存产品数量
            $instock_count = get_instock_product_count_for_cat( $category_id );
            echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .' '. $instock_count .'</a>';
        }       
    }

    return ob_get_clean();
}
add_shortcode( 'newcats', 'newcats_shortcode' );

关键说明

  1. 辅助函数逻辑:通过WP_Query筛选出指定分类下、发布状态、库存状态为instock的产品,返回匹配到的总数量。如果你的店铺需要严格检查库存数量大于0,可以取消注释代码中的库存数量条件。
  2. 输出缓冲优化:使用ob_start()和ob_get_clean()包裹短代码输出,避免直接echo可能导致的内容位置错乱问题,符合WordPress短代码的最佳实践。
  3. 子分类控制:include_children参数可控制是否统计子分类下的有库存产品,根据你的业务需求调整即可。

内容的提问来源于stack exchange,提问作者Muhammad S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:45:36