How to exclude pages from wp_nav_menu

The wp_nav_menu is a pretty awesome feature in WP.  Not only It let you to create your desired custom menu, but also other customization. However, the exclude page feature is missing in the default wp_nav_menu accepted parameters . This mean we have to do a little trick to make it do so.

From the WP documentation, we can see that by default the “fallback_cb” is pointing at  ‘wp_page_menu’ . This is the element that we need to do our trick.

<?php $defaults = array(
	'theme_location'  => '',
	'menu'            => '', 
	'container'       => 'div', 
	'container_class' => 'menu-{menu slug}-container', 
	'container_id'    => '',
	'menu_class'      => 'menu', 
	'menu_id'         => '',
	'echo'            => true,
	'fallback_cb'     => 'exclude_page_fallback',// pointing to our own function 
	'before'          => '',
	'after'           => '',
	'link_before'     => '',
	'link_after'      => '',
	'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
	'depth'           => 0,
	'walker'          => ''
); ?>

<?php wp_nav_menu( $defaults ); ?>

So instead let fallback_cb poiting at default ‘wp_page_menu’, we create a custom function for it. In this function, we will include the ‘wp_page_menu’ and as we can see from the documentation of wp_page_menu, it does accept exclude parameter. Hence this is where we define which pages we want to exclude.

In your function.php add this lines:

// this is the fallback for our own menu
function exclude_page_fallback() {
	wp_page_menu( 'show_home=Home&exclude=17,52,32' );//exclude your page here. you can also include pages as well. Refer to the documentation to see what other things you can play with
}

That’s all!

1 Comment

  1. Jascha

    Nice idea, but it wont work if you have a created a custom menu. The fallback just shows when there is no menu, so its not suitable to exclude a page from a custom menu 🙁 thanks anyway

Leave A Comment