Woocommerce mini cart ajax update

Here’s the quick and dirty.

<br />
add_filter('woocommerce_add_to_cart_fragments', 'your_own_add_to_cart_fragment');</p>
<p>function your_own_add_to_cart_fragment( $fragments ) {<br />
	global $woocommerce;<br />
	ob_start();<br />
	?&gt;<br />
        //Update basket counter<br />
	&lt;div class=&quot;basket-counter&quot;&gt;&lt;?php echo WC()-&gt;cart-&gt;get_cart_contents_count(); ?&gt;&lt;/div&gt;<br />
	&lt;?php<br />
	$fragments['.basket-counter'] = ob_get_clean();<br />
	return $fragments;<br />
}<br />

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

<br />
function your_own_add_to_cart_fragment( $fragments ) {<br />
	global $woocommerce;<br />
	ob_start();<br />
	?&gt;<br />
        //Replace header logo with cart contents count<br />
	&lt;div class=&quot;header__logo&quot;&gt;&lt;?php echo WC()-&gt;cart-&gt;get_cart_contents_count(); ?&gt;&lt;/div&gt;<br />
	&lt;?php<br />
        //Element to be replaced<br />
	$fragments['.header__logo'] = ob_get_clean();<br />
	return $fragments;<br />
}<br />

To review

Get Woocommerce object

<br />
global $woocommerce;<br />

Start output buffer

<br />
ob_start();<br />

New content to display on add to cart

<br />
&lt;?php echo $my_new_content; ?&gt;<br />
//Remember the Fragment node is replaced so you need to wrap content in html element.<br />

Note: $fragment Key is used to find node to be replaced. So you could do something like:

<br />
    $fragments['.basket-counter'] = ob_get_contents();<br />
    $fragments['.header__logo &gt; strong, .basket-counter'] = ob_get_contents();</p>
<p>

Notice I used

ob_get_contents()
instead of
ob_get_clean()

That’s really all there is to it.

Leave a Reply