Flush the Object Cache From the Admin Bar
Adds a toolbar button for administrators that empties the object cache (Redis, Memcached or the built-in cache) after deployments or data fixes.
Opens WPIDE on
Code
add_action( 'admin_bar_menu', function ( $bar ) {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$bar->add_node( array(
'id' => 'wpide-flush-cache',
'parent' => 'top-secondary',
'title' => wp_using_ext_object_cache() ? 'Flush object cache' : 'Flush cache',
'href' => wp_nonce_url( admin_url( 'admin-post.php?action=wpide_flush_cache' ), 'wpide_flush_cache' ),
) );
}, 999 );
add_action( 'admin_post_wpide_flush_cache', function () {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( 'Sorry, you are not allowed to do that.' );
}
check_admin_referer( 'wpide_flush_cache' );
wp_cache_flush();
wp_safe_redirect( add_query_arg( 'wpide_cache_flushed', '1', wp_get_referer() ? wp_get_referer() : admin_url() ) );
exit;
} );
add_action( 'admin_notices', function () {
if ( isset( $_GET['wpide_cache_flushed'] ) && current_user_can( 'manage_options' ) ) { // phpcs:ignore WordPress.Security.NonceVerification
echo '<div class="notice notice-success is-dismissible"><p>Object cache flushed.</p></div>';
}
} );
Notes
Flushing a shared persistent cache affects every site using it; on multisite it clears the whole network's cache.
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.