Here’s the quick and dirty.
1 2 3 4 5 6 7 8 9 10 11 12 | 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
1 2 3 4 5 6 7 8 9 10 11 | 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
1 | global $woocommerce ; |
Start output buffer
1 | ob_start(); |
New content to display on add to cart
1 2 | <?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:
1 2 3 | $fragments [ '.basket-counter' ] = ob_get_contents(); $fragments [ '.header__logo > strong, .basket-counter' ] = ob_get_contents(); |
Notice I used
1 | ob_get_contents() |
instead of
1 | ob_get_clean() |
That’s really all there is to it.