I want to plain to cache a page menu, that takes about 50 queries on page load.
At the moment I have cache setting code with Transient API
$housemenu = get_transient('housemenu_key');
if (!$housemenu) {
$housemenu = wp_nav_menu(
array(
'menu' => '',
'menu_class' => 'sf-menu',
'menu_id' => 'nav',
'walker' => new description_walker()
)
);
echo 'not-set';
set_transient(
'housemenu_key',
$housemenu,
60*60*3
);
}
echo $housemenu;
$housemenu = get_transient('housemenu_key');
returns a nothing. If i set like this:
$housemenu = 'return corrent';
echo 'not-set';
All works perfect. Why this menu is not working? Menu can be a walker transient?
Use: WordPress 3.8
wp_nav_menu()
doesn’t return anything by default, it just echoes out formatted html.For
wp_nav_menu()
to return a value you will need to pass'echo' => false
into it’s arguments, like so:It should be noted that by caching the entire menu in a transient, you will lose it dynamic nature. For instance if it cached it while on your home page all of the active classes applied to the menu items will ALWAYS reflect the home page. Thus if you were to visit a different page the active classes on the menu items would be wrong.
This will cause quite a bit of pain if you wish to convey via CSS which page the current user is on.
By default
wp_nav_menu()
echoes result and returns nothing. You need to set'echo' => false
in its arguments to flip the behavior and be able to assign result to a variable.one problem exists there… WordPress has built-in page detection, to give the CSS classes to current page in menu… and if cached, then your navigation menu-items will never get “current-page” class or etc..
however, there are 2 solutions:
Solution 1
Before caching, once, add classes to
<a>
items:and then cache the menu… it will have such output:
so, attach “current-item” class from javascript (in page body you should pass variable to javascript, to find out if you are on a post,page,category or etc..)… i.e.:
solution 2
for typical,non wp-sites.
i have tried to code a JS script, which may solve the problem..
So, in case you cache the menu, and want to get “current-menu-item” class, then put this function in your page source/cache (better to be in the end of body):
at first, add this code in header(better inside .js file):
and determine your desired style to the attached class