Tuesday 18th July 2023

How to stop WooCommerce calling admin-ajax.php on all page loads to improve performance.

WooCommerce makes a call to admin-ajax.php on every page view, to retrieve shopping cart data. As this happens asynchronously, the page view can still be cached – which is great, but the request back to admin-ajax.php can’t be and results in a full un-cached load of WordPress and WooCommerce for reach request.

Quite a lot of solutions we’ve seen involve removing the dynamic cart from the page, but we agreed with our client’s marketing team that this would harm conversions – so we looked for an alternative.

After a little digging, we noticed that WooCommerce sets several cookies when there is something in the visitor’s cart. By monitoring those, we can determine if the visitor has a cookie set and know if we need to update the cart information on the page.

/**
 * Prevents WooCommerce making a call to admin-ajax to update the cart contents when the cart is
 * empty/non-existent by testing for the existence of the 'woocommerce_cart_hash' cookie first.
 *
 * @return void
 */
function dm_smarter_ajax_cart_check() {
	global $wp_scripts;

	$handle = 'wc-cart-fragments';
	if ( isset( $wp_scripts->registered[ $handle ] ) && $wp_scripts->registered[ $handle ] ) {

		$load_cart_fragments_path = $wp_scripts->registered[ $handle ]->src;
		$wp_scripts->registered[ $handle ]->src = null;
		wp_add_inline_script(
			'jquery',
			'
			function dm_get_cookie(name) {
			  var v = document.cookie.match("(^|;) ?" + name + "=([^;]*)(;|$)");
			  return v ? v[2] : null;
			}

			function dm_load_cart_fragments_if_cart_active() {
			  var cart_src = "' . $load_cart_fragments_path . '";
			  var script_id = "dm_loaded_wc_cart_fragments";
			  if (document.getElementById(script_id) !== null) {
			    return false;
			  }

			  if (dm_get_cookie("woocommerce_cart_hash")) {
			    var script = document.createElement("script");
			    script.id = script_id;
			    script.src = cart_src;
			    script.async = true;
			    document.head.appendChild(script);
			  }
			}

			dm_load_cart_fragments_if_cart_active();
			document.addEventListener("click", function() { setTimeout(dm_load_cart_fragments_if_cart_active, 1000); });
			'
		);
	}
}
add_action( 'wp_enqueue_scripts', 'dm_smarter_ajax_cart_check', PHP_INT_MAX - 1 );

If you own a WooCommerce store that’s performing slowly, visit our WooCommerce development page to find out how we can help. If you are an in-house developer or agency looking for help tackling a specific problem or additional support – you may want to find out more about how we offer support WordPress for developers.

We design and develop all kinds of great stuff using WordPress, WooCommerce & LearnDash.

If you are looking for a new WordPress website, WooCommerce store or LearnDash LMS or want to improve an existing one, give us a call on 0114 303 8181 or click the button below to get the ball rolling.