Instantly share code, notes, and snippets.

Embed
What would you like to do?
Timing for the WordPress menu cache
<?php
/**
* WordPress menu cache timing.
*
* @package BJ\Menu
* @author bjornjohansen
* @version 0.1.0
* @license https://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU General Public License version 2 (GPLv2)
*/
/**
* Add the logging timer.
*
* @param string|null $output Nav menu output to short-circuit with. Default null.
* @param stdClass $args An object containing wp_nav_menu() arguments.
* @return string|null Output passthrough (default null).
*/
add_filter( 'pre_wp_nav_menu', function( $output, $args ) {
global $wp_menu_generation_start;
$wp_menu_generation_start = microtime( true );
return $output;
}, 9, 2 );
/**
* Log the menu generation time if we have a cache hit.
*
* @param string|null $output Nav menu output to short-circuit with. Default null.
* @param stdClass $args An object containing wp_nav_menu() arguments.
* @return string|null Output passthrough (default null).
*/
add_filter( 'pre_wp_nav_menu', function( $output, $args ) {
if ( ! is_null( $output ) ) {
global $wp_menu_generation_start;
$wp_menu_generation_time = microtime( true ) - $wp_menu_generation_start;
write_log( sprintf( 'Cache hit: Menu output was fetched in %d ms', round( $wp_menu_generation_time * 1000 ) ) );
}
return $output;
}, 11, 2 );
/**
* Log the menu generation time.
*
* @param string $nav_menu The HTML content for the navigation menu.
* @param stdClass $args An object containing wp_nav_menu() arguments.
*/
add_filter( 'wp_nav_menu', function( $nav_menu, $args ) {
global $wp_menu_generation_start;
$wp_menu_generation_time = microtime( true ) - $wp_menu_generation_start;
write_log( sprintf( 'Cache miss: Menu output was generated in %d ms', round( $wp_menu_generation_time * 1000 ) ) );
return $nav_menu;
}, 11, 2 );
@bjornjohansen

This comment has been minimized.

Copy link
Owner

bjornjohansen commented Jan 20, 2018

This will break horribly if you don’t have a write_log() implementation. Here’s a really simple one: https://gist.github.com/bjornjohansen/f4bd788d4d7a4172f5a9c539f4d09e47

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