14 Comments

WordPress wp_nav_menu to Exclude Page(s)

While working on a project I realised that I need to exclude pages I created from the top menu, which is built by wp_nav_menu function in header.php. I could use Menus under Appearance tab to define a top menu and pass the menu name in the function arguments but I would loose the CSS for the original menu created by wp_nav_menu itself. So I started looking for ways to exclude the pages I don’t want to show on the top menu. So I kind of added a hack in wp_nav_menu function.

First, I added “exclude” in the list of default arguments:

$defaults = array( 'menu' => '', 'container' => 'div', 'container_class' => '', 'container_id' => '', 'menu_class' => 'menu', 'menu_id' => '', 'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'depth' => 0, 'walker' => '', 'theme_location' => '', 'exclude' => '' );

Then I copied couple of lines from wp_list_pages function (in post-template.php) to add the $exclude_array variable:

$exclude_array = ( $args->exclude ) ? explode(',', $args->exclude) : array();
$args->exclude = implode( ',', apply_filters('wp_nav_menu_excludes', $exclude_array) );

Note that I had the change $args['exclude'] to $args->exclude. Now in header.php just add the exclude in the argument array:

< ?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary', 'exclude' => '66' ) ); ?>

Done! The unwanted pages are gone from the top menu. Booyaaah!