Skip to content

Instantly share code, notes, and snippets.

@mikejolley
Forked from jameskoster/header.php
Last active November 12, 2024 15:49
Show Gist options
  • Save mikejolley/2044109 to your computer and use it in GitHub Desktop.
Save mikejolley/2044109 to your computer and use it in GitHub Desktop.
WooCommerce - Update number of items in cart and total after Ajax
<?php
// Ensure cart contents update when products are added to the cart via AJAX (place the following in functions.php)
add_filter( 'woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment' );
function woocommerce_header_add_to_cart_fragment( $fragments ) {
ob_start();
?>
<a class="cart-contents" href="<?php echo wc_get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf (_n( '%d item', '%d items', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>
<?php
$fragments['a.cart-contents'] = ob_get_clean();
return $fragments;
}
@akmahaz11
Copy link

@rajanit2000, This is the issue, the header cart is not getting updated... how can i resolve this?

@akmahaz11
Copy link

@rajanit2000, I am using Flatsome woocommerce theme

@rajanvijayan
Copy link

Can you please share your header.php file via email?

@akmahaz11
Copy link

@rajanit2000, Ihave sent email for you ... please check your mail inbox

@hovek
Copy link

hovek commented Feb 3, 2020

I've added throw new Exception('In function.'); to test if the function woocommerce_header_add_to_cart_fragment is being called and it's never called. Why?

@ruman
Copy link

ruman commented Aug 24, 2021

To make this hook work perfectly just consider 2 things.

  1. set unique classname for the navbar cart icon like <div class="nav-cart"><i class="fa fa-busket"></i><span class="nav-cart-total"> <?php $count;?></span>/div>
  2. in that filter have to edit this:
$cart_count = WC()->cart->cart_contents_count;
<span class="nav-cart-total"><?php echo $cart_count; ?></span>
	
	<?php $fragments['span.nav-cart-total'] = ob_get_clean(); ?>

Will work delightfully!!!

@rvpatel
Copy link

rvpatel commented Jan 21, 2022

Why not work on cart page and how to fix easy way?

@rvpatel
Copy link

rvpatel commented Jan 21, 2022

Update count when cart page with ajax update.

jQuery(document.body).on('removed_from_cart updated_cart_totals', function () {
		$(document.body).trigger('wc_fragment_refresh');
});

@rafiul
Copy link

rafiul commented Apr 15, 2022

@rajanvijayan Working perfectly. Thank you.

@katjusca
Copy link

Please auttakaa joku en tiedä onko tämä oikea paikka kysyä mutta minun Supercell ID on lukittu ja kun yritän mennä sinne uudella sähköpostilla ja id:llä tulee vaan anna palautuskoodit mistä mä voin löytää ne koodit ja miten mä voin päästä sinne omalle tilille ne takaisin kyseessä on hay day koodit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment