Halloween Sale 15% off Ends in See the plans
PHP

Object Cache Hit Rate in the Admin Bar

Shows administrators the object cache hit rate, hits and misses for the current page in the admin bar, to check whether Redis or Memcached is actually helping.

Don’t have WPIDE yet? Install it on your site

Code

// Added just before the bar renders, so most of the page's cache calls are counted.
add_action( 'wp_before_admin_bar_render', function () {
    global $wp_object_cache, $wp_admin_bar;

    if ( ! current_user_can( 'manage_options' ) || ! is_object( $wp_object_cache ) || ! $wp_admin_bar ) {
        return;
    }

    $hits   = isset( $wp_object_cache->cache_hits ) ? (int) $wp_object_cache->cache_hits : 0;
    $misses = isset( $wp_object_cache->cache_misses ) ? (int) $wp_object_cache->cache_misses : 0;
    $total  = $hits + $misses;
    $rate   = $total ? round( $hits / $total * 100, 1 ) : 0;

    $wp_admin_bar->add_node( array(
        'id'     => 'wpide-object-cache',
        'parent' => 'top-secondary',
        'title'  => esc_html( sprintf( 'Cache %s%% %s', $rate, wp_using_ext_object_cache() ? '(persistent)' : '(runtime)' ) ),
        'meta'   => array( 'title' => sprintf( '%d hits, %d misses', $hits, $misses ) ),
    ) );
} );

Notes

Without a persistent object cache the numbers only cover the current request.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.