Updated- 2018 年 8 月 - 更轻、紧凑的代码版本。
类似的新答案:
Woocommerce 3 中的自定义购物车项目按产品类别计数 https://stackoverflow.com/questions/51775962/custom-cart-item-counts-by-product-category-in-woocommerce-3/51777457#51777457
此函数用于显示特定产品类别的购物车数量:
function cat_cart_count( $cat_name ) {
$count = 0; // Initializing
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
if( has_term( $term, 'product_cat', $cart_item['product_id'] ) )
$count += $cart_item['quantity'];
}
// Returning category count
return $count == 0 ? false : $count;
}
您将上面的代码粘贴到活动子主题或主题的 function.php 文件中。
For "shorts"
类别,您将这样使用它:cat_cart_count( "shorts" )
并将取代WC()->cart->get_cart_contents_count()
.
注意:自 woocommerce 3 起,WC()->cart->get_cart_url();
被替换为wc_get_cart_url()
.
用它定制片段代码"tshirts"
and "short"
类别:
<a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf (_n( '%d t-shirt', '%d t-shirts', cat_cart_count( "tshirt" ) ), cat_cart_count( "tshirt" ) ); ?> - <?php echo sprintf (_n( '%d short', '%d shorts', cat_cart_count( "shorts" ) ), cat_cart_count( "shorts" ) ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>
由于 woocommerce 刷新的购物车片段使用 html 标签类“cart-contents”,因此您可能需要按照以下说明重命名它:Woocommerce 3 中的自定义购物车项目按产品类别计数 https://stackoverflow.com/questions/51775962/custom-cart-item-counts-by-product-category-in-woocommerce-3/51777457#51777457
在我们定制的代码片段中的最后一件事,您可以按照自己的方式定制它,添加一些文本或其他东西......我已经替换"item(s)"
按类别名称。