Woocommerce add to cart ajax and mini-cart

RomkaLTU picture RomkaLTU · Oct 11, 2016 · Viewed 10.5k times · Source

I need to re-populate mini-cart when product added via ajax add to cart. I manage to update cart quantity with filter woocommerce_add_to_cart_fragments like this:

add_filter( 'woocommerce_add_to_cart_fragments', function($fragments) {

    ob_start();
    ?>

    <div class="cart-contents">
        <?php echo WC()->cart->get_cart_contents_count(); ?>
    </div>

    <?php $fragments['div.cart-contents'] = ob_get_clean();

    return $fragments;

} );

And my HTML markup is

<div class="cart-contents">
    <?php echo WC()->cart->get_cart_contents_count(); ?>
</div>

Bellow that is hidden div witch showing on .cart-contents hover

<div class="header-quickcart"><?php woocommerce_mini_cart(); ?></div>

I want to update this div content same way or similar to woocommerce_add_to_cart_fragments. Or should I change HTML markup and hold everything in 1 div? What is common way or best practice to doing that?

Answer

RomkaLTU picture RomkaLTU · Oct 11, 2016

Ok so I just realized that I can use woocommerce_add_to_cart_fragments filter 2 times, like so:

add_filter( 'woocommerce_add_to_cart_fragments', function($fragments) {

    ob_start();
    ?>

    <div class="cart-contents">
        <?php echo WC()->cart->get_cart_contents_count(); ?>
    </div>

    <?php $fragments['div.cart-contents'] = ob_get_clean();

    return $fragments;

} );

add_filter( 'woocommerce_add_to_cart_fragments', function($fragments) {

    ob_start();
    ?>

    <div class="header-quickcart">
        <?php woocommerce_mini_cart(); ?>
    </div>

    <?php $fragments['div.header-quickcart'] = ob_get_clean();

    return $fragments;

} );

First updating quantity and aother refreshing mini-cart view.