Updated - August 2018 - Lighter and compact code version.
Similar new answer:
Custom cart item counts by product category in Woocommerce 3
This function is made to display the cart count for a specific product category:
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;
}
You will paste the code above to the function.php file of your active child theme or theme.
For "shorts"
category you will use it this way: cat_cart_count( "shorts" )
and will replace WC()->cart->get_cart_contents_count()
.
Note: Since woocommerce 3, WC()->cart->get_cart_url();
is replaced by wc_get_cart_url()
.
Customizing the snippet code with it for "tshirts"
and "short"
categories:
<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>
As the html tag class "cart-contents" is use by woocommerce refreshed cart fragments, you might need to rename it as explained in: Custom cart item counts by product category in Woocommerce 3
Last thing in our customized snippet code, you can customize-it your way adding some text or additional thingsā¦ I have replace "item(s)"
by the category name.