Performance PHP Intermediate

Cache Navigation Menus

Store the HTML of large classic menus in the object cache, and clear it whenever a menu is saved.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 23 lines
// 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' );
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

How it works

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.

Things to watch

  • Without a persistent object cache, WordPress’s cache only lasts for one request, so this snippet does nothing useful. Check Tools → Site Health for “You should use a persistent object cache”.
  • Menus that change per user, such as showing “My account” when logged in, need the user’s login state added to the key.
  • Block-based Navigation blocks don’t use these filters.

How to test it

With Query Monitor active, load a page twice. The menu’s queries should only appear on the first load.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only