LiteSpeed is likely the fastest growing web server of the year for 2019. It provides a powerful caching engine with a robust WordPress plugin that can greatly speed up any WordPress site. It’s Edge Side Includes (ESI) are particularly cutting edge, allowing you to “punch holes” in a publicly-cached page, and then fill those holes with privately-cached content.

Although it is rather straightforward to turn WordPress shortcodes into ESI blocks and there is a helpful interface for turning WordPress widgets into ESI bocks, it’s not quite so easy to turn a WordPress menu into a LiteSpeed ESI block.

Thankfully, with a little help from the LiteSpeed Wiki article on Third Party Plugin Integrations and a perusal of their ESI blocks code samples, I was able to create a not-too-complicated function to fill this very need!

Let’s assume my WordPress theme is using the standard wp_nav_menu() function to insert a menu with the ID of “menu-id-to-replace” into a header template. The following code in your theme’s functions.php file would turn that menu into an ESI block, privately cached for each unique website visitor.

The basic logic goes like this: If WordPress is building a regular page (not an individual ESI block), use the wp_nav_menu() filter to override the normal output of the “menu-id-to-replace” menu and instead insert the contents of the “my_custom_menu_esi_hook” block. If WordPress is building the “my_custom_menu_esi_hook” block, we insert the code to display the wp_nav_menu “menu-id-to-replace”.

To take this a step further, I created the following WordPress plugin that will privately cache the Divi theme’s primary and secondary navigation menus as LiteSpeed ESI blocks. Check it out!