Search code examples
ajaxwoocommercehook-woocommercecart

Wrong hook used when adding cart counter to site header


I'm trying to insert a cart counter in the header of a WooCommerce website, and have found that the code I used was breaking the checkout process (payment options were grayed out.)

Apparently my choice of hook "wp" was a bad choice. I've been combing through WooCommerce filter and action documentation and I still haven't found anything except for "wp" which resulted in the intended code being echoed.

Here is what I was using:

function d_cart_counter() {
    if (is_single() || is_page() || (is_product() && !is_admin()) || (is_shop() && !is_admin())) {
        global $woocommerce;
        $cartcount = $woocommerce->cart->get_cart_contents_count();
        echo '<span id="d-cart-count" style="display:none;">'.$cartcount.'</span>';
    }
}
add_action('after_body_open_tag', 'd_cart_counter', 99 );

jQuery was used to copy the value from this span to another part of the DOM.

But again, it worked at the cost of breaking the payment system. Can anybody tell me how to properly hook this into WooCommerce? Many thanks.


Solution

  • You want to use the filter 'woocommerce_add_to_cart_fragments'

    Add your HTML for the cart counter in your site

    <span class="d-cart-count">0</span>
    

    Then something like this

    function update_cart_via_woo_fragments($fragments_array) {
        
        $fragments_array['span.d-cart-count'] = '<span class="d-cart-count">' . sprintf(_n('%d', '%d', WC()->cart->get_cart_contents_count()), WC()->cart->get_cart_contents_count()) . '</span>';
    
        return $fragments_array;
    }
    
    add_filter('woocommerce_add_to_cart_fragments', 'update_cart_via_woo_fragments', 10, 1);