Skip to content

Instantly share code, notes, and snippets.

@heyfletch
Created January 27, 2022 18:53
Show Gist options
  • Save heyfletch/22f71847c4ca4ee82ac595e679f7135e to your computer and use it in GitHub Desktop.
Save heyfletch/22f71847c4ca4ee82ac595e679f7135e to your computer and use it in GitHub Desktop.
Purge Multiple WordPress Caches in Ideal Order
<?php
// Clears Page Cache at key moments, e.g., after plugin updates
// Importantly, it clears the page when WP Rocket clears cache
// If Cloudflare page caching is enabled, this clears the nginx page cache before Cloudflare's cache
add_action( 'before_rocket_clean_domain', 'fd_purge_all_cache', 10, 0 ); // Before WP Rocket Cache
add_action( 'upgrader_process_complete', 'fd_purge_all_cache', 10, 0 ); // After plugin updates
add_action( 'activated_plugin', 'fd_purge_all_cache', 10, 0 ); // After plugin activated, doesn't work?
add_action( 'deactivated_plugin', 'fd_purge_all_cache', 10, 0 ); // After plugin deactivated, broken?
add_action( 'switch_theme', 'fd_purge_all_cache', 10, 0 ); // After theme changed, untested
// Purge All Caches
function fd_purge_all_cache()
{
// CSS Cache (Elementor)
if ( class_exists( 'Elementor' ) ) {
do_action( 'elementor/core/files/clear_cache' );
}
// Used CSS Cache (Perfmatters)
if ( class_exists( 'Perfmatters\CSS' ) ) {
Perfmatters\CSS::clear_used_css();
}
// Object Cache
if ( function_exists( 'wp_cache_flush' ) ) {
wp_cache_flush();
}
// Page Cache (nginx)
if ( function_exists( 'purge_all' ) ) {
global $nginx_purger;
if ( isset( $nginx_purger ) ) {
$nginx_purger->purge_all();
}
}
// Used CSS Cache (WP Rocket)
wpr_clear_used_css();
}
// Clear Used CSS (WP Rocket)
function wpr_clear_used_css() {
if ( defined( 'WP_ROCKET_VERSION' ) ) {
// access rocket's injection container
$container = apply_filters( 'rocket_container', null );
// get the rucss subscriber from the container
$subscriber = $container->get( 'rucss_admin_subscriber' );
// call the truncate method.
$subscriber->truncate_used_css();
}
}
@heyfletch
Copy link
Author

This clears the main caches that may get stuck while using Elementor with Nginx Page Caching, Object Caching, WP Rocket, Perfmatters, and Cloudflare. It's currently dependent on WP Rocket to clear Cloudflare's cache, and currently uses the Nginx Helper and GridPane Redis Object Cache plugins.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment