Turn a WordPress Menu into a LiteSpeed ESI Block

by | Jan 7, 2020 | WordPress Tweaks

*** Post Updated 10/30/2022 to work with the latest LiteSpeed Cache for WordPress API *** 

LiteSpeed is growing in popularity and came in second as the web server of the year for 2021. 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 classic 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 LSCache for WordPress API and a perusal of their ESI blocks code samples, I was able to create a simple 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 menu using wp_nav_menu (and it’s not building the ESI block), we 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-esi-menu” block.

If WordPress is building the “my-esi-menu” block, we insert the HTML code to display the menu.

As an example, I modified the above code to set the Astra theme’s secondary user navigation menu to be a LiteSpeed ESI block.