How to clear cache via cron job

In this Article

WP Rocket provides custom functions for clearing and preloading the cache. In order to run these at specific times each day you can use a cron job on your server.

Set Up a Cron Job

  1. If you want to make sure that cache is cleared at a certain time every day, you must first create a cron job through your web hosting control panel (check this video as a quick guide) and launch it at whatever time you want.
  2. Instead of pointing to wp-cron (as in the tutorial above), you will set your cron job to point to the specific file you create and upload in the next step. Make sure to specify the correct path to your custom file, rocket-clean-domain.php, in your cron job settings.

Clear cache

  1.  Create a PHP file and name it (for example): rocket-clean-domain.php
  2. To clear the cache for the whole site, use the following code in your file:
  3. <?php 
    // Load WordPress.
    require( 'wp-load.php' );
    
    // Clear cache.
    if ( function_exists( 'rocket_clean_domain' ) ) {
    	rocket_clean_domain();
     }
    	
  4. Upload this file to your WordPress installation's root ( where wp-config.php and wp-load.php are located).
  5. Note: If you place it in a different location, you need to edit the path in require( 'wp-load.php' ); above to match its location.

  6. Make sure to specify the correct path to your new file rocket-clean-domain.php in your cron job settings.

Alternative Code Snippets

You may use one of the following code snippets in case you want to also preload the cache, or clear a specific page instead of the whole cache.

Clear cache and trigger preload

In the example above the code provided will only clear the cache, but not preload it. In order to trigger a preload, use run_rocket_sitemap_preload(). Make sure a sitemap URL is set in your WP Rocket options.

<?php 
// Load WordPress.
require( 'wp-load.php' );

// Clear cache.
if ( function_exists( 'rocket_clean_domain' ) ) {
	rocket_clean_domain();
}

// Preload cache.
if ( function_exists( 'run_rocket_sitemap_preload' ) ) {
	run_rocket_sitemap_preload();
}

Clear and Preload a Specific Page

Instead of clearing the whole cache you can clear a specific URL with the following code snippet. Make sure to: 

  • Replace '30' with your specific page ID. 
  • Replace https://example.com/page with the specific URL you want to preload.
<?php 
// Load WordPress.
require( 'wp-load.php' );
 
// Clear specific page cache
if ( function_exists( 'rocket_clean_post' ) ) {
	rocket_clean_post('30');
 }
 
// Preload page 
wp_remote_get ('https://example.com/page');
Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.