WooCommerce: How to Alter Cart Items Count

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        businessbloomer.com/woocommerce-customization
 * @author        Rodolfo Melogli, Business Bloomer
 * @testedwith    WooCommerce 4.6
 * @community     https://businessbloomer.com/club/
 */

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

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

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

3 thoughts on “WooCommerce: How to Alter Cart Items Count

  1. Hi, the snipet show this error:
    Warning: call_user_func_array() expects parameter 1 to be a valid callback, function ‘almapet_alter_cart_contents_count’ not found or
    invalid function name …

      1. Good to know!

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

Your email address will not be published. Required fields are marked *