I'm creating a website where the users can add a product to cart (using ajax) from homepage. I'm using a JS function to do this, and it's working. Also, I have a function that updates the custom cart counter from header.
If i'm on Shop or Cart page, the woocommerce fragments works perfectly, updating my custom cart counter. But when I'm on homepage, the cart counter just updates if I refresh any other page.
I tried to trigger the fragments event after the triggering of 'added_to_cart' event, as you can see below, but it did'nt worked.
Javascript Function that triggers the event 'added_to_cart' on homepage
$('.homepage_add_to_cart_button').on('click', function(e) {
e.preventDefault();
$thisbutton = $(this);
id = $(this).val();
addToCart(id);
return false;
});
function addToCart(p_id) {
var data = {
action: 'ql_woocommerce_ajax_add_to_cart',
product_id: p_id,
};
$.ajax({
type: 'post',
url: '?add-to-cart='+p_id,
data: data,
beforeSend: function (response) {
$thisbutton.removeClass('added').addClass('loading');
},
complete: function (response) {
$thisbutton.addClass('added').removeClass('loading');
},
success: function (response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $thisbutton]);
$(document.body).trigger('wc_fragment_refresh');
}
},
});
}
I'm using this code on functions.php of woocommerce fragments to update the custom cart counter that I have on header.
function holistic_refresh_cart_count($fragments) {
ob_start();
?>
<span class="header-cart-count">
<?php echo WC()->cart->get_cart_contents_count(); ?>
</span>
<?php
$fragments['.header-cart-count'] = ob_get_clean();
return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'holistic_refresh_cart_count');