如何在WooCommerce前端显示指定分类的总库存产品数?
WooCommerce指定分类库存产品数量统计代码修复提示
语法错误修复:你的代码末尾多了一个多余的
},这会直接触发PHP语法报错,删除该闭合大括号即可。添加分类存在性校验:
get_term_by可能因分类slug错误、分类不存在返回false或错误对象,直接调用$term->term_id会引发致命错误,需先做判断:$term = get_term_by('slug', 'furniture', 'product_cat'); if ( !$term || is_wp_error($term) ) { echo '指定分类不存在'; return; }优化查询效率(替代循环统计):原代码循环所有产品统计库存的方式在产品量大时效率极低,建议直接通过元查询筛选库存大于0的产品,结合分类查询直接获取总数:
$args = array( 'post_type' => 'product', 'posts_per_page' => -1, 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $term->term_id, 'include_children' => true ) ), 'meta_query' => array( array( 'key' => '_stock_status', 'value' => 'instock', 'compare' => '=' ), // 补充判断库存数量大于0(避免部分产品状态为instock但库存为0的情况) array( 'key' => '_stock', 'value' => 0, 'type' => 'numeric', 'compare' => '>' ) ), 'fields' => 'ids' // 仅获取产品ID,进一步提升查询效率 ); $products = new WP_Query($args); $count = $products->found_posts; // 直接获取符合条件的产品总数,无需循环 echo '库存产品数量:' . $count; wp_reset_postdata();可变产品库存统计(可选):若分类包含可变产品,上述代码仅统计父产品,如需统计所有有库存的子变体,可添加以下逻辑:
// 查询分类下有库存的产品变体 $variation_args = array( 'post_type' => 'product_variation', 'posts_per_page' => -1, 'post_status' => 'publish', 'meta_query' => array( array( 'key' => '_stock_status', 'value' => 'instock', 'compare' => '=' ), array( 'key' => '_stock', 'value' => 0, 'type' => 'numeric', 'compare' => '>' ) ), 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $term->term_id, 'include_children' => true ) ) ); $variations = new WP_Query($variation_args); $variation_count = $variations->found_posts; // 总库存数量 = 简单产品库存数 + 有库存的变体数 $total_count = $count + $variation_count; echo '库存产品总数(含变体):' . $total_count;
内容的提问来源于stack exchange,提问作者Hype
相关产品推荐
相关产品推荐

