Menus and Object Caching

Continuing the discussion from Making accessible menus:

What I do is save each menu output in a transient. See

If there’s a difference between a menu when logged-in and logged-out, then I also save the output of each of those in its own transient. As with all caching, it’s important to ensure that the transients get deleted automatically whenever the menu needs updating, and it’s also useful to provide a manual method (though you could use the Transients Manager or the WP Optimize plugins for the manual method instead).

I like to give my transients a long lifetime but the precise length doesn’t matter much to me. If a menu needs updating, its transient will get automatically deleted anyway.

This method on its own speeds sites up tremendously and (depending on the menu size) can cut down dramatically on the number of database queries.

But if you have Memcached or Redis installed on your server, you can then connect up your site to use one of them, and they will automatically take control of all the transients for full object caching. My host uses Litespeed servers, so this is easy for me because I can just use the Litespeed Cache WordPress plugin, configure its Advanced Settings to use Memcached, and voilà!


Thanks, would get back to you if I am successful with that :slight_smile:

How do you save those? Are you using a filter which runs right before a menu is output in the frontend site, or while its being updated / saved in the backend, or some different / combined method alltogether?

cu, w0lf.

I use the wp_nav_menu filter to set the transient, and the pre_wp_nav_menu filter to get it.

It seems like transients would defeat the purpose, since each transient is two database entries (versus one entry for the menu item), and core does some object caching of its own (not sure which tables). But perhaps it’s because core caches the options table, where transients are stored, and not the posts table, where menu items are stored.

I didn’t say I was caching each menu item with a transient. I am caching the whole menu with a transient. So if the menu has many items, this method reduces the number of database calls from tens or hundreds down to just two per menu.

Just try it for yourself and see the difference.

And then, yes, you’re right, this method also gets the benefit of using the options table rather than the posts table. And then it gets the benefit of Memcached if you use that. So, all in all, it provides a significant boost, especially if you have menus with a large number of items.