Store the HTML of large classic menus in the object cache, and clear it whenever a menu is saved.
// Reuse a cached menu if there is one.
add_filter( 'pre_wp_nav_menu', function ( $output, $args ) {
$key = nahnu_menu_cache_key( $args );
$cached = wp_cache_get( $key, 'nahnu_menus' );
return false === $cached ? $output : $cached;
}, 10, 2 );
// Store the menu after WordPress builds it.
add_filter( 'wp_nav_menu', function ( string $html, $args ): string {
wp_cache_set( nahnu_menu_cache_key( $args ), $html, 'nahnu_menus', HOUR_IN_SECONDS );
return $html;
}, 10, 2 );
// The key includes the page URL, so "current page" classes stay correct.
function nahnu_menu_cache_key( $args ): string {
$version = (int) wp_cache_get( 'version', 'nahnu_menus' );
return md5( $version . serialize( (array) $args ) . ( $_SERVER['REQUEST_URI'] ?? '' ) );
}
// Clear every cached menu when any menu is saved.
add_action( 'wp_update_nav_menu', function (): void {
wp_cache_set( 'version', time(), 'nahnu_menus' );
} );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
Big mega menus with dozens of items run several database queries and a lot of PHP on every page. If you use a persistent object cache like Redis or Memcached, this snippet stores the finished menu HTML and reuses it.
The pre_wp_nav_menu filter runs before WordPress builds a menu. If cached HTML exists for the same menu settings and page, it’s returned and the build is skipped. Otherwise WordPress builds the menu and the wp_nav_menu filter stores it for an hour.
The cache key includes the current URL, so each page keeps its correct “current menu item” highlighting. Saving any menu bumps a version number, which makes every old cached copy unused.
With Query Monitor active, load a page twice. The menu’s queries should only appear on the first load.