Auto clear Autoptimize cache before it gets too large

 In Functions, WordPress Plugins

Autoptimize “makes optimizing your site really easy. It can aggregate, minify and cache scripts and styles, injects CSS in the page head by default (but can also defer), moves and defers scripts to the footer and minifies HTML”, thank you to the plugin authors they have done a great job in making this plugin available and free for everyone. The plugin is almost perfect but Autoptimize does not have its proper cache purging mechanism, “as this could remove optimized CSS/JS which is still referred to in other caches, which would break your site”.

Autoptimize plugin cache size can grow out of control rapidly before you can notice and that can become a huge problem for your WordPress site. On this post you will find two different approaches to tackle this “issue”.

The code snippet below added to your theme functions .php will limit the Autoptimize cache to 256MB.

Thank you to @rahulpragma to make the below snippet available

# Automatically clear autoptimizeCache if it goes beyond 256MB
if (class_exists('autoptimizeCache')) {
    $myMaxSize = 256000; # You may change this value to lower like 100000 for 100MB if you have limited server space
    $statArr=autoptimizeCache::stats(); 
    $cacheSize=round($statArr[1]/1024);
    
    if ($cacheSize>$myMaxSize){
       autoptimizeCache::clearall();
       header("Refresh:0"); # Refresh the page so that autoptimize can create new cache files and it does breaks the page after clearall.
    }
} 

This code snippet below added to your theme functions .php will schedule cron jobs to delete the cache every week and month. This code snippet is a bit different from the above this code only cleans up the cache it doesn’t limit the size of it.

<?php
namespace wppress;
class GarbageCollection
{
    public function __construct()
    {
        add_filter('cron_schedules', function ($schedules) {
            $schedules['weekly'] = array(
                'interval' => 604800,
                'display'  => __('Once a Week'),
            );
            $schedules['monthly'] = array(
                'interval' => 2635200,
                'display'  => __('Once a month'),
            );
            return $schedules;
        });
        if (!wp_next_scheduled('wppress/garbage/clear')) {
            wp_schedule_event(time(), 'monthly', 'wppress/garbage/clear');
        }
        add_action('wppress/garbage/clear', [ &$this, 'clear']);
    }
    public function clear()
    {
        if (class_exists('\autoptimizeCache')) {
            /* Clear autoptimize cache once a month */
            \autoptimizeCache::clearall();
        }
    }
}
new GarbageCollection();
?>

Recent Posts
Showing 6 comments
  • webdev
    Reply

    This is not working.
    I have tried this on my site.

    • Nuno Morais Sarmento
      Reply

      Hi there,

      Thank you for passing by on my website and for trying to use my code snippet. What is the log output of your cronjob?

  • Tony
    Reply

    Do you know if this would clear all the caches on a multisite network if Autoptimize is active network-wide or just the primary site?

    • Nuno Morais Sarmento
      Reply

      Hi Tony, thank you for your comment and for passing by on my website. You can pack this code snippet into a plugin and activate the plugin network-wide. Let me know if you need help to do that.

  • Dan
    Reply

    Where should I post the code. Htaccess?

    • Nuno Morais Sarmento
      Reply

      Hi Dan, thank you for passing by on my website. The code should be added in your theme functions .php/

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Start typing and press Enter to search

Let's work together

I'd love to work with you! Please fill out my project form to tell me more about your project/work. I reply to all enquiries within 48 hours.

Availability

  • October - Available
  • November - Available
  • December - Booked

Rates

  • My day rate is £300.
  • I can provide a fixed price for your work.

EN - Header Enquiry Form

  • This form collects your name, email address and telephone number so that I can respond to the enquiry(ies) that you submit via this website. Please check my privacy policy for the full story on how I use, protect and manage your submitted data.