Ludwig Wendzich

Tricking Wordpress' wp_nav_menu() into thinking it is on a different page

I came across a situation where we needed to trick wp_nav_menu() in thinking it was on a particular page.

(In this case we set a page template to show blog posts and wanted those blog posts to have the .current flags. We’re also running them through a Custom Walker to only show sub-menus.)

wp_nav-menu() uses $wp_query->get_queried_object() instead of $post so you need to replace $wp_query just before your wp_nav_menu() call and restore it right after.

<?php global $wp_query;

//Save for later
$_wp_query = $wp_query;

//Replace with query for the page you want to masquerade as
$wp_query=new WP_Query( 'page_id=20' );

//Loading WordPress Custom Menu
wp_nav_menu( array(
 'menu'            => 'main-menu',
 'walker' => new Walker_SubNav_Menu()
) ); 

//Restore wp_query
$wp_query = $_wp_query; ?>

Now we need to rewrite our Walker_SubNav_Menu() to replace $post locally with the $wp_query->get_queried_object() before it references $post.

global $wp_query;

//Change local $post
$post = $wp_query->get_queried_object();

(If we don’t, it will call the global $post which Wordpress has set to the original $wp_query->get_queried_object() earlier on.)

And voila. Wordpress temporarily thinks it’s on a different page, renders the menu as if it is on that page and the you restore it’s memory to the correct $wp_query.