How to update cart using ajax – WooCommerce

Mostly E-commerce shops display cart content in header or in sidebar, for better user accessibility. Now when ever user adds a new product to the cart the cart needs to be updated. This happens when you refresh the page. But what if in WooCoomerce, you want to update the cart content (total items, total price etc) using Ajax.

You must be thinking that you might have to write much of a manual coding  combination of ajax, php , javascript. But no worries you do not have to write that much of code. You can use “woocommerce_add_to_cart_fragments” filter provided by WooCoomerce inbuilt.

If you want to display normal cart content this use following code in your template file:

<a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf (_n( '%d item', '%d items', WC()->cart->cart_contents_count ), WC()->cart->cart_contents_count ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>

If you want to ajaxify it then simply write this code in your functions.php fiile

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()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf (_n( '%d item', '%d items', WC()->cart->cart_contents_count ), WC()->cart->cart_contents_count ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>             
	$fragments['a.cart-contents'] = ob_get_clean();
	
	return $fragments;
}

Now call following function in your header.php or your desired place.

woocommerce_header_add_to_cart_fragment($fragments)

That’s it. Now cart will be updated via ajax. No need to refresh page. Happy Coding !!!!!

Advertisements

2 thoughts on “How to update cart using ajax – WooCommerce

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s