WooCommerce: add to cart without page reload using AJAX
WooCommerce can add products to the cart without reloading the page, but a custom cart link in the header doesn’t know about it: the item count and total stay the same until the next page load. The woocommerce_add_to_cart_fragments filter fixes that by refreshing your cart markup after every AJAX cart update.
Problem: How do you add a product to the cart without reloading the page, and keep the cart count in the header up to date?
Step 1. Enable AJAX add to cart
In WooCommerce → Settings → Products, enable Enable AJAX add to cart buttons on archives. Simple products on shop and category pages are then added to the cart without a reload. (On single product pages the standard button submits the form; to make it AJAX too you need custom JavaScript or a plugin.)
Step 2. Add a cart link to the template
Place a cart link wherever you need it, for example in header.php:
<a class="cart-contents" href="<?php echo esc_url( wc_get_cart_url() ); ?>"
title="<?php esc_attr_e( 'View your shopping cart', 'woocommerce' ); ?>">
<?php
$count = WC()->cart->get_cart_contents_count();
echo esc_html( sprintf( _n( '%d item', '%d items', $count, 'woocommerce' ), $count ) );
echo ' – ' . WC()->cart->get_cart_total();
?>
</a>
Step 3. Refresh the link after AJAX updates
Add this to functions.php. After every AJAX cart event WooCommerce requests the fragments and replaces the elements matched by each array key with the new HTML:
add_filter( 'woocommerce_add_to_cart_fragments', 'helloadmin_cart_fragment' );
function helloadmin_cart_fragment( $fragments ) {
ob_start();
?>
<a class="cart-contents" href="<?php echo esc_url( wc_get_cart_url() ); ?>"
title="<?php esc_attr_e( 'View your shopping cart', 'woocommerce' ); ?>">
<?php
$count = WC()->cart->get_cart_contents_count();
echo esc_html( sprintf( _n( '%d item', '%d items', $count, 'woocommerce' ), $count ) );
echo ' – ' . WC()->cart->get_cart_total();
?>
</a>
<?php
$fragments['a.cart-contents'] = ob_get_clean();
return $fragments;
}
To avoid keeping the same markup in two places, move it into a function, say helloadmin_cart_link(), and call it both from the template and from the filter.
Notes
- The array key (
a.cart-contents) is a CSS selector, and it must match the element in the template. You can change the tag and class names, as long as they stay the same in both places; otherwise WooCommerce can’t find the element and the cart link looks stuck. - Older tutorials use
WC()->cart->get_cart_url()andWC()->cart->cart_contents_count. Both are deprecated: usewc_get_cart_url()andWC()->cart->get_cart_contents_count().