Auto clear Autoptimize cache before it gets too large

 In Functions, WordPress Plugins

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. The code below will schedule cron jobs to delete every week and month.

<?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 2 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?

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

  • August - Limited
  • September - Available
  • October - Available

Rates

  • My day rate is £300.
  • I can provide a fixed price for your work.
  • Projects start at around £2,000.

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.