Cache Free Cart Total
November 21, 2024 · AI Conversations
### Steps:
1. **Disable Caching for the Function**
If you're using caching plugins like WP Super Cache or W3Speedster, they might cache the output of this function. You can use hooks provided by these plugins to exclude this function or its output.
2. **Modify the Function Output**
Ensure that the `et_show_cart_total` function directly retrieves fresh data every time it is called instead of using any cached values.
3. **Bypass Cache in WP Super Cache**
Add this snippet to your theme’s `functions.php` file to exclude the cart page or related function output from being cached:
add_filter('wp_cache_request_uri', function ($uris) {
if (is_cart() || is_checkout()) {
$uris[] = $_SERVER['REQUEST_URI'];
}
return $uris;
});
4. **Force Dynamic Data with Ajax**
Modify the `et_show_cart_total` function to use an Ajax call for fetching the cart total dynamically. This ensures that it always retrieves the latest cart data, bypassing any cached content.
Example Code:
add_action('wp_enqueue_scripts', function () {
wp_enqueue_script('cart-total-refresh', get_template_directory_uri() . '/js/cart-total.js', ['jquery'], null, true);
wp_localize_script('cart-total-refresh', 'cartTotal', [
'ajax_url' => admin_url('admin-ajax.php'),
]);
});
add_action('wp_ajax_refresh_cart_total', 'refresh_cart_total');
add_action('wp_ajax_nopriv_refresh_cart_total', 'refresh_cart_total');
function refresh_cart_total() {
$cart_total = et_show_cart_total(); // Assume this function fetches the latest cart total
wp_send_json_success(['total' => $cart_total]);
}
And in the `cart-total.js` file:
jQuery(document).ready(function ($) {
$.ajax({
url: cartTotal.ajax_url,
type: 'POST',
data: { action: 'refresh_cart_total' },
success: function (response) {
if (response.success) {
$('#cart-total').text(response.data.total); // Update cart total dynamically
}
}
});
});
5. **Disable Fragment Caching (Optional)**
WooCommerce uses fragment caching for cart totals. If your `et_show_cart_total` relies on WooCommerce, you might need to disable WooCommerce cart fragment caching:
add_filter('woocommerce_cart_fragment_refresh_delay', '__return_zero');
These steps should make the `et_show_cart_total` function retrieve fresh data dynamically and avoid being served from cache.