Shoora
4/14/2019 - 7:23 PM

Simple Wordpress plugin that checks the Autoptimize plugin's cache every 6 hours and clears the cache if it's above a maximum size specified

Simple Wordpress plugin that checks the Autoptimize plugin's cache every 6 hours and clears the cache if it's above a maximum size specified.

<?php
/**
 * The plugin bootstrap file
 *
 * This file is read by WordPress to generate the plugin information in the plugin
 * admin area. This file also includes all of the dependencies used by the plugin,
 * registers the activation and deactivation functions, and defines a function
 * that starts the plugin.
 *
 * @link              http://example.com
 * @since             0.0.1
 * @package           Autoptimize_Clear_Cache
 *
 * @wordpress-plugin
 * Plugin Name:       Autoptimize Clear Cache
 * Plugin URI:        https://briannadeleasa.com
 * Description:       Automatically clears the Autoptimize cache when it grows to a large size.
 * Version:           1.0.0
 * Author:            Brianna Deleasa
 * Author URI:        http://briannadeleasa.com
 * License:           GPL-2.0+
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 * Text Domain:       autoptimize-clear-cache
 * Domain Path:       /languages
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
    die;
}


add_action( 'init', 'aocc_init_clear_cache_check' );
/**
 * Checks whether we've cleared the cache yet (via a transient). If not,
 * clear the cache and set the transient.
 *
 * @since 1.0.0
 * 
 * @param null
 * @return null
 */
function aocc_init_clear_cache_check() {

    // Get any existing copy of our transient data
    if ( false === ( $special_query_results = get_transient( 'aocc_cache_cleared' ) ) ) {
        set_transient( 'aocc_cache_cleared', $special_query_results, 6 * HOUR_IN_SECONDS );

        // Clear the cache because we haven't done it already
        aocc_clear_cache();
    }

}


/**
 * Function that clears the Autoptimize cache.
 *
 * @since 1.0.0
 * 
 * @param $max_size int
 * @return null
 */
function aocc_clear_cache( $max_size = 256000 ) {

    if ( class_exists('autoptimizeCache') ) {
        $statArr = autoptimizeCache::stats();
        $cacheSize = round( $statArr[1] / 1024 );

        if ( $cacheSize > $max_size ) {
            autoptimizeCache::clearall();
            header("Refresh:0"); # Refresh the page so that autoptimize can create new cache files and it does breaks the page after clearall.
        }
    }

}