Limit Amount of Menu Items in WordPress

If your theme uses wp_nav_menu to pull in a menu a user set in your Theme Location, but you want to limit the max number of top-level menu items, then this code is exactly what you need.

For example, we tested a theme that supports menus, and has a “mainmenu” theme location, to pull in a menu as the mainmenu / top nav on the site. But, due to the design / css (fixed-width), there’s only room for a maximum of 7 items in the top level of whatever menu is pulled in.

This solution uses a filter to do that to ANY theme you choose to use.

add_filter( 'wp_nav_menu_objects', 'mytheme_menufilter', 10, 2 );
function mytheme_menufilter($items, $args) {
	// want our MAINMENU to have MAX of 7 items
	if ( $args->theme_location == 'mainmenu' ) {
		$toplinks = 0;
		foreach ( $items as $k => $v ) {
			if ( $v->menu_item_parent == 0 ) {
				// count how many top-level links we have so far...
			// if we've passed our max # ...
			if ( $toplinks > 7 ) {
	return $items;

Comments  Leave a Reply

  1. > then this code is exactly what you need.

    What code?

    1. Hey Brad,
      I just updated the post with the snippet.

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!