One "Clear Cache" Button for Any Caching Plugin
Adds a single "Clear all caches" toolbar button for administrators that clears whichever cache plugin is active (WP Rocket, LiteSpeed Cache, W3 Total Cache, WP Super Cache, WP Fastest Cache or SG Optimizer) plus the object cache.
Opens WPIDE on
Code
add_action( 'admin_bar_menu', function ( $bar ) {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$bar->add_node( array(
'id' => 'wpide-clear-all-caches',
'title' => esc_html__( 'Clear all caches' ),
'href' => wp_nonce_url( add_query_arg( 'action', 'wpide_clear_all_caches', admin_url( 'admin-post.php' ) ), 'wpide_clear_all_caches' ),
) );
}, 95 );
add_action( 'admin_post_wpide_clear_all_caches', function () {
check_admin_referer( 'wpide_clear_all_caches' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'Sorry, you are not allowed to do that.' ), 403 );
}
$cleared = array();
if ( function_exists( 'rocket_clean_domain' ) ) {
rocket_clean_domain();
$cleared[] = 'WP Rocket';
}
if ( defined( 'LSCWP_V' ) ) {
do_action( 'litespeed_purge_all' );
$cleared[] = 'LiteSpeed';
}
if ( function_exists( 'w3tc_flush_all' ) ) {
w3tc_flush_all();
$cleared[] = 'W3 Total Cache';
}
if ( function_exists( 'wp_cache_clear_cache' ) ) {
wp_cache_clear_cache();
$cleared[] = 'WP Super Cache';
}
if ( isset( $GLOBALS['wp_fastest_cache'] ) && method_exists( $GLOBALS['wp_fastest_cache'], 'deleteCache' ) ) {
$GLOBALS['wp_fastest_cache']->deleteCache( true );
$cleared[] = 'WP Fastest Cache';
}
if ( function_exists( 'sg_cachepress_purge_cache' ) ) {
sg_cachepress_purge_cache();
$cleared[] = 'SG Optimizer';
}
wp_cache_flush();
$cleared[] = 'object cache';
set_transient( 'wpide_cleared_' . get_current_user_id(), implode( ', ', $cleared ), 60 );
wp_safe_redirect( wp_get_referer() ? wp_get_referer() : admin_url() );
exit;
} );
add_action( 'admin_notices', function () {
$key = 'wpide_cleared_' . get_current_user_id();
$done = get_transient( $key );
if ( $done ) {
delete_transient( $key );
echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( sprintf( 'Cleared: %s.', $done ) ) . '</p></div>';
}
} );
Notes
Handy on agency sites where different clients use different cache plugins. Only administrators see it.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.