X

How to Limit Amount of Menu Items in WordPress

Snippets by IsItWP

Are you looking for a way to limit amount of menu items? While there’s probably a plugin for this, we have created a quick code snippet that you can use to 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 WordPress theme you choose to use.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

<?php
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...
				$toplinks++;
			}
			// if we've passed our max # ...
			if ( $toplinks > 7 ) {
				unset($items[$k]);
			}
		}
	}
	return $items;
}
?>

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 9 best WordPress real estate plugins and How to secure your WordPress forms.

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 Cancel reply

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!