Home » WooCommerce: How to Alter Cart Items Count

WooCommerce: How to Alter Cart Items Count

by Tutor Aspire

We’ve already seen how to exclude hidden products from the WooCommerce Mini-Cart widget counter; today I want to expand on the same concept and try to recalculate / alter such counter based on custom criteria.

For example, some business models require to count the number of distinct items in the Cart, no matter their respective cart quantities. So, if there are 2x “Item 1” and 4x “Item 2”, this altered counter would show 1+1=2 and not 2+4=6. So, let’s see how this is done – enjoy!

Counter should show “7” but instead it shows “3”. That’s what the WooCommerce snippet below does

PHP Snippet: Custom Cart Item Count @ WooCommerce Mini Cart Header Widget

/**
 * @snippet       Alter Cart Counter @ WooCommerce Cart Widget
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @testedwith    WooCommerce 4.6
 * @donate $9     https://www.tutoraspire.com
 */

add_filter( 'woocommerce_cart_contents_count', 'tutoraspire_alter_cart_contents_count', 9999, 1 );

function tutoraspire_alter_cart_contents_count( $count ) {
$count = count( WC()->cart->get_cart() );
return $count;
}

You may also like