s Ajaxify your WooCommerce shopping cart widget - Boshanka

Ajaxify your WooCommerce shopping cart widget

Ajaxify your WooCommerce shopping cart widget

WooCommerce is probably one of the most valuable and useful plugins in any WordPress designer’s arsenal. Offering amazingly simple integration and a plethora of features and bolt-ons. Truly you can create a hugely complex e-commerce solution that’s elegant and lightening fast.

I’ve been adding e-commerce to this site using the wonderful WooCommerce, and had set the “add items to the cart via AJAX when on a product page” in WooCommerce settings. Problem is, the cart widget, also shown on that same page, wasn’t updating at the same time.

Well i found the answer, and it’s incredibly simple.

First up – add this to your theme wherever you want your cart to display (you could even use a text widget – with extended PHP functionality.)

1
2
3
<?php global $woocommerce; ?>

<a class="cart-contents" href="<?php echo $woocommerce->cart->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>

Then just add this to your “functions.php” file and your cart widget will magically become ajaxed – so when you add items from the category page, your cart total will update on the fly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php add_filter('add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment');

function woocommerce_header_add_to_cart_fragment( $fragments ) {
global $woocommerce;
ob_start();
?>
<a class="cart-contents" href="<?php echo $woocommerce->cart->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-contents'] = ob_get_clean();

return $fragments;

}

?>

14 Responses to "Ajaxify your WooCommerce shopping cart widget"

Leave a Reply

Enjoyed this article?

If you enjoyed this article please rate & share.

You Might Also Like