How to Ajaxify Woocommerce Cart for Automatic Cart Update
Generally, when you create Woocommerce supported themes from the scratch, you need to show a cart in the top header. Mostly a tiny piece of code is used to show the cart. But not sufficient when you want to update cart item and price automatically when a product added or removed. That is why you need to Ajaxify cart.
How to Ajaxify Woocommerce Cart
Generally, this code will show a cart in themes. Although it doesn’t update automatically cart item and price.
<a class="cart-customlocation" 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>
Rather, to update price and product automatically, add this code in functions.php, then it will update cart when a product added or removed.
// Ensure cart contents update when products are added to the cart via AJAX (place the following in functions.php). // Used in conjunction with https://gist.github.com/DanielSantoro/1d0dc206e242239624eb71b2636ab148 // Compatible with WooCommerce 3.0+. Thanks to Alex for assisting with an update! function woocommerce_header_add_to_cart_fragment( $fragments ) { global $woocommerce; ob_start(); ?> <a class="cart-customlocation" href="<?php echo esc_url(wc_get_cart_url()); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> - <?php echo $woocommerce->cart->get_cart_total(); ?></a> <?php $fragments['a.cart-customlocation'] = ob_get_clean(); return $fragments; }
Code Explanation
First, you need to add a custom function using add_filter to current Woocommerce function “add_to_cart_fragments”.
Second, use ajax so that the script will not send a request to another page. According to PHP manual “The ob_start() function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.”
The $fragments parameter gets the ob_get_clean() to obtain current buffer contents and deletes the output buffer.