Here’s the quick and dirty.
add_filter('woocommerce_add_to_cart_fragments', 'your_own_add_to_cart_fragment');
function your_own_add_to_cart_fragment( $fragments ) {
global $woocommerce;
ob_start();
?>
//Update basket counter
<div class="basket-counter"><?php echo WC()->cart->get_cart_contents_count(); ?></div>
<?php
$fragments['.basket-counter'] = ob_get_clean();
return $fragments;
}
So what’s happening here?
Woocomerce will find the Fragment node and replace it with the output buffer.
That means we can update any element using the add_to_cart button.
Yes any..
Want to replace the logo with the total amount of items in the basket? No problem
function your_own_add_to_cart_fragment( $fragments ) {
global $woocommerce;
ob_start();
?>
//Replace header logo with cart contents count
<div class="header__logo"><?php echo WC()->cart->get_cart_contents_count(); ?></div>
<?php
//Element to be replaced
$fragments['.header__logo'] = ob_get_clean();
return $fragments;
}
To review
Get Woocommerce object
global $woocommerce;
Start output buffer
ob_start();
New content to display on add to cart
<?php echo $my_new_content; ?> //Remember the Fragment node is replaced so you need to wrap content in html element.
Note: $fragment Key is used to find node to be replaced. So you could do something like:
$fragments['.basket-counter'] = ob_get_contents();
$fragments['.header__logo > strong, .basket-counter'] = ob_get_contents();
Notice I used
ob_get_contents()
instead of
ob_get_clean()
That’s really all there is to it.