Search code examples
ajaxwordpresswoocommerceflatsomewp-rocket

Flatsome Theme: How to use Page Caching and not cache the cart item count in Mini Cart


I have a problem with the Flatsome Theme (Version: 3.18.4). When I enable WP-Rocket page caching, the cart item count gets cached in the HTML too. How can I use page caching to make my site faster and prevent the cart item count from being cached?

Flatsome Cart with Item count

Some sources recommend removing the woocommerce_items_in_cart from the Never Cache cookie list. However, this causes the HTML to stop loading from the page cache and slows down the site whenever a user adds an item to their cart.


Solution

  • Solution

    1. Use or create a child theme for the Flatsome theme
    2. Inside the child theme folder, create a subfolder called \template-parts\header\partials
    3. Copy the file element-cart-mobile.php (flatsome\template-parts\header\partials) from Flatsome theme to the subfolder of your child theme.
    4. Open the copied file in a text editor and delete the following code snippets from line 46 and line 57 respectively: data-icon-label="<?php echo WC()->cart->cart_contents_count; ?>"
    5. Save the file and activate the child theme. This will override the original element-cart-mobile.php file from the Flatsome theme with your modified version.

    Explanation

    The problem is lies in the flatsome\template-parts\header\partials\element-cart-mobile.php file.

    The code in line 46 and 57: data-icon-label="<?php echo WC()->cart->cart_contents_count; ?>" cause the cart item count to be added in the html. This breaks the page cache because the mini carts are displayed on every page. Since they are displayed on every page, the page cache of each page becomes invalid if the cart item count changes.

    This can be safely removed because the Ajax JavaScript (I am not sure which JS file exactly is doing this) automatically updates the cart item count of the mini cart. The cart item count may appear a second later after the page loads, which is a minor issue compared to the page caching not working.

    enter image description here