I am not going to start with pointless intro about WooCommerce and how many sites WooCommerce powers. If you're reading this post you know for sure what it does so I will just dive in.

In a recent update of our WooCommerce plugin which allows bulk product adding we've added Ajax add to cart so the clients can stay on the same page in case they want to add more products a few seconds later. This has to be enabled from the plugin's Settings which can be found in WP Admin > Settings > Orbisius Quick Order for WooCommerce.

One of our customers & also great beta tester Annie (Hi Annie) noticed that the WooCommerce cart-contents widget wasn't refreshing i.e. the user adds one or more products to the shopping cart, the page correctly doesn't refresh but the widget that shows the current total didn't change at all. Same thing for mobile view as well. This was happening with the Storefront theme.

I started digging into WooCommerce & Storefront theme and found the piece of code that was responsible for triggering and refreshing the so called fragments. WooCommerce makes an Ajax call and receives a JSON back . The JSON nicely includes with different fields that contain HTML code that can be used to replace different sections on the page. A theme or a plugin can/will handle the add to cart and make some (visual) changes.

The code that reloads those fragments can be found here: \plugins\woocommerce\assets\js\frontend\cart-fragments.js

To refresh WooCommerce widget you have to copy the code below

[code]
var $fragment_refresh = {
url: wc_cart_fragments_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'get_refreshed_fragments' ),
type: 'POST',
success: function( data ) {
if ( data && data.fragments ) {

$.each( data.fragments, function( key, value ) {
$( key ).replaceWith( value );
});

if ( $supports_html5_storage ) {
sessionStorage.setItem( wc_cart_fragments_params.fragment_name, JSON.stringify( data.fragments ) );
set_cart_hash( data.cart_hash );

if ( data.cart_hash ) {
set_cart_creation_timestamp();
}
}

$( document.body ).trigger( 'wc_fragments_refreshed' );
}
}
};
[/code]

... and to trigger the event you do this:

[code]
$.ajax( $fragment_refresh );
[/code]

or

[code]
jQuery.ajax( $fragment_refresh );
[/code]

Note: if you have this snippet code in php you may have to rename $fragment_refresh to my_plugin_fragment_refresh so the dollar sign $ doesn't get interpreted as php variable.

Ideal way

It would have been awesome if we can trigger the fragments to reload with a simple custom jQuery event and not to have to copy and paste code above.

[code]
$( document.body ).trigger( 'wc_reload_fragments' );
[/code]

or

[code]
$( document.body ).trigger( 'wc_force_reload_fragments' );
[/code]

Referral Note: When you purchase through a referral link (if any) on this page, we may earn a commission.
If you're feeling thankful, you can buy me a coffee or a beer