Skip to content

Instantly share code, notes, and snippets.

@bjornjohansen
Created January 20, 2018 17:49
Show Gist options
  • Save bjornjohansen/cf886d7b9a649195d0c60fcf11e99d98 to your computer and use it in GitHub Desktop.
Save bjornjohansen/cf886d7b9a649195d0c60fcf11e99d98 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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