Search code examples
ajaxwordpresswoocommercespinnercart

WooCommerce quantity for different products only - header mini cart - count(WC()->cart->get_cart())


Having problem implementing changes for the total quantity of products in the header mini cart.

Currently woocommerce calculate total qty for all products in cart:

echo WC()->cart->get_cart_contents_count();

We need a solution which will calculate qty for different products only. So we have modified code:

echo count(WC()->cart->get_cart());

That is working fine, qty is shown show by different products only, but now we have AJAX bug, spinner keep loading and page need a manual refresh. After refresh products are successfully added to cart and mini cart is updated with new product qty calc.

What could be a problem with stopping AJAX from working properly?


Solution

  • Resolved with different approach by adding a hook callback. Working perfectly.

     /**
     * @snippet     WC Mini Cart / Product Quantity Calculation by Unique Products - Excluding the same products 
     * @author      Rkoms
    **/
    
    // define the woocommerce_cart_contents_count callback 
    function filter_woocommerce_cart_contents_count($unique_product_qty) { 
        // make filter magic happen here... 
        $unique_product_qty = count(WC()->cart->get_cart());
        return $unique_product_qty; 
    };          
    // add the filter 
    add_filter( 'woocommerce_cart_contents_count', 'filter_woocommerce_cart_contents_count', 15, 1 );