我找到了this script这允许我在 WooCommerce 中的购物车图标上方显示购物车内容总数:
<a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf (_n( '%d item', '%d items', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>
如果我的购物车中有 100 件商品,它会显示 100。
我真正想要的是按项目类型显示计数。因此,如果有 50 件 T 恤和 50 件短裤,我希望这 2 种商品类型能够单独显示。
有谁知道我怎样才能实现这个目标?
谢谢
最佳答案
Updated - August 2018 - Lighter and compact code version.
Similar new answer: Custom cart item counts by product category in Woocommerce 3
此函数用于显示特定产品类别的购物车数量:
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 文件中。
对于 "shorts"
类别,您将这样使用它:cat_cart_count( "shorts")
和将替换 WC()->cart->get_cart_contents_count()
。
Note: Since woocommerce 3,
WC()->cart->get_cart_url();
is replaced bywc_get_cart_url()
.
使用它为“tshirts”
和“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”,因此您可能需要按照以下说明重命名它:Custom cart item counts by product category in Woocommerce 3
我们的自定义代码片段中的最后一件事,您可以按照自己的方式自定义它,添加一些文本或其他内容...我已将 "item(s)"
替换为类别名称。
关于php - WooCommerce:按产品类别划分的自定义购物车项目计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37862126/