Auto clear Autoptimize cache before it gets too large

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 doesn’t offer a proper schedule purging mechanism. 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.
    }
}

The code snippet below added to your theme functions .php will schedule Cron job 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.


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();

ABOUT AUTHOR

Nuno

Hi, I'm a Freelance Web Developer and WordPress Expert based in London with a wealth of website development and support experience. I am great at problem solving and developing quick solutions.

20 thoughts on “Auto clear Autoptimize cache before it gets too large

  • webdev Reply

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

    13th July 2018 at 12:23 pm
    • 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?

      20th July 2018 at 10:44 am
  • 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?

    28th September 2018 at 8:51 am
    • 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.

      28th September 2018 at 9:37 am
  • Dan Reply

    Where should I post the code. Htaccess?

    6th October 2018 at 3:07 pm
    • Nuno Morais Sarmento Reply

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

      7th October 2018 at 1:25 pm
  • çıplak yazar Reply

    Thank you so much. I was lookıng for this code.

    12th December 2019 at 7:39 am
  • Patrick Reply

    This is great, thank you – exactly what I needed. Nowhere in the Autoptimize documentation was there anything about autoptimizeCache::clearall(); function… I was under the impression there was no way to trigger the cache clear other than through wp-admin or via some janky workaround that are smattered all over the net. Appreciate it!

    18th December 2019 at 6:48 pm
    • Nuno Morais Sarmento Reply

      I’m glad I was able to help you 🙂

      19th December 2019 at 9:50 am
  • apachx Reply

    Hi. Thank you for the first code. But i still have a question: how to clear all cache of “WP Super Cache” plugin too?

    22nd January 2020 at 10:31 pm
    • Nuno Morais Sarmento Reply

      Hi, you need to go to your Wp-admin area and click Settings under Settings click WP Super Cache –> Contents –> Delete Cache

      23rd January 2020 at 5:24 pm
      • apachx Reply

        I mean programmatically. By php code in functions.php file.

        23rd January 2020 at 7:14 pm
        • Nuno Morais Sarmento Reply

          This may help you – https://w-shadow.com/blog/2008/10/22/cache-cleaner-for-wp-super-cache/

          24th January 2020 at 9:38 am
  • Riccardo Luigi Reply

    Hi Nuno,
    first of all thanks for the snippets.

    However I’m a little bit confused about the second one: you say to put it in functions.php but the tags “” at the end suggest it should be copied into a stand-alone php file.

    What’s the right thing to do?

    3rd April 2020 at 9:15 pm
    • Nuno Morais Sarmento Reply

      Hi Riccardo,

      Thank you for passing by on my website. Yes, you right, it could mislead people. The code is now amended.

      3rd April 2020 at 9:31 pm
  • Michael Macneil Reply

    Hi Nuno

    Does the top code-snippet need to be wrapped in a function and added as an action? (If so, which one!)

    15th June 2020 at 1:00 pm
    • Nuno Morais Sarmento Reply

      Hi Michael,

      I think for both examples you won’t need to wrap in a function, just add one of the examples to your theme functions.php.

      15th June 2020 at 1:09 pm
  • Velimir Reply

    Hi Nuno,

    Thank you for this post. I appiciate your effort. I use first solutio but after x amount of mb when cache need to be cleared, webiste keep autorefreh without deleting cache, and it’s stuck in the loop and refreshes website. Any idea why this is so? Thank you for your time.

    14th November 2020 at 1:05 pm
    • Nuno Morais Sarmento Reply

      Hi Velimir,

      No sure what is that happening. Try this plugin https://en-gb.wordpress.org/plugins/autoclear-autoptimize-cache/. Probably is all what you need 🙂

      14th November 2020 at 1:10 pm
      • Velimir Reply

        Hi Nuno,

        Thank you for fast answer. First I will try with second snipet. Thank you one more time.

        14th November 2020 at 2:20 pm

Leave a Reply

Your email address will not be published. Required fields are marked *

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

  • LET'S TALK!

    Fill in the form below to make an enquiry or find my contact details on my contact page.

  • Hidden
  • This field is for validation purposes and should be left unchanged.