Let Editors Clear the WP Rocket Cache
Adds a "Clear page cache" item to the toolbar for editors, who normally cannot purge WP Rocket, protected with a nonce and limited to clearing the page they are viewing.
Opens WPIDE on
Code
add_action( 'admin_bar_menu', function ( $bar ) {
if ( is_admin() || ! function_exists( 'rocket_clean_files' ) || ! current_user_can( 'edit_others_posts' ) || current_user_can( 'manage_options' ) ) {
return;
}
$url = home_url( add_query_arg( array() ) );
$bar->add_node( array(
'id' => 'wpide-rocket-clear',
'title' => esc_html__( 'Clear page cache' ),
'href' => wp_nonce_url( add_query_arg( array( 'action' => 'wpide_rocket_clear', 'url' => rawurlencode( $url ) ), admin_url( 'admin-post.php' ) ), 'wpide_rocket_clear' ),
) );
}, 90 );
add_action( 'admin_post_wpide_rocket_clear', function () {
check_admin_referer( 'wpide_rocket_clear' );
if ( ! current_user_can( 'edit_others_posts' ) || ! function_exists( 'rocket_clean_files' ) ) {
wp_die( esc_html__( 'Sorry, you are not allowed to do that.' ), 403 );
}
$url = isset( $_GET['url'] ) ? esc_url_raw( rawurldecode( wp_unslash( $_GET['url'] ) ) ) : '';
if ( $url && wp_parse_url( $url, PHP_URL_HOST ) === wp_parse_url( home_url(), PHP_URL_HOST ) ) {
rocket_clean_files( array( $url ) );
}
wp_safe_redirect( $url ? $url : home_url( '/' ) );
exit;
} );
Notes
Administrators already have WP Rocket's own menu. Change edit_others_posts to another capability if needed.
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.