Automatically clear autoptimize cache without plugin

Automatically clear autoptimizeCache

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.

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


# Automatically clear autoptimizeCache if it goes beyond 256MB – allservice-wp.com
if (class_exists(‘autoptimizeCache’)) {
$myMaxSize = 256000; # clear Autoptimize cache to 256MB
$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.
}
}