2
votes

I found this script that allows me to show cart content total above the shopping cart icon within 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>

If there are 100 items in my cart it shows 100.

What I really want is to display the count by item types. So if there are 50 t-shirts and 50 shorts, I want that 2 item types count to be displayed individually.

Does anyone knows how I can achieve this?

Thanks

1

1 Answers

3
votes

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.