Ask your WordPress questions! Pay money and get answers fast! (more info)

How to limit the number of top level menu items in the admin/ backend area of WordPress WordPress



So I know how to limit the number of top level menu items, on the front end of WordPress websites using php. I would like to know how to do this in the backend/ admin area for menus.

So when logged into WordPress, & using the dragging feature to add more pages to be a top level item in my menu, it will make it clear that the allowed number of top level menu items has been reached. I understand that this will have to be done wih JavaScript, as there aren't any appropriate hooks for the admin/ backend menu editor. The menu is called 'primary'.

So I talking about Javascript for

Can anyone provide some JavaScript that will limit the number of top level menu items in the BACKEND/ ADMIN area please. Screen shot shows the admin area which is where I would like the Javascript to display the limit set please. So for example, if the top level menu item limit is 6, it will warn the WordPress user if they try to add a 7th top level menu item. Ideally, I would like it to prevent them from adding any more top level menu items above the limit, although I need it to communicate to the user what is happening, so they don't get confused by this.

Answers (1)


Reigel Gallarde answers:

this goes to your functions.php

function custom_admin_js() {
$screen = get_current_screen();
if ( $screen->id != 'nav-menus' )
<script type="text/javascript">
var warn = false;
$('.submit-add-to-menu').on('click', function(){
var num_menu = $('#menu-to-edit').children('.menu-item-depth-0').length;
num_menu += $('.menu-item-checkbox:checked').length;
if ( !warn && ( num_menu > 6 ) ) {
warn = true;
alert('warning: Top level menu Items are limited to 6!');

$('#update-nav-menu').on('submit', function(){
var num_menu = $('#menu-to-edit').children('.menu-item-depth-0').length;
if ( num_menu > 6 ) {
alert('error: Top level menu Items are limited to 6!');
return false;
add_action('admin_footer', 'custom_admin_js');

This will prevent saving the menu if top level menu items are more than 6.
They can add more but will not trigger save, instead will show a warning that 'Top level menu Items are limited to 6!'.

Let me know what you think.

mattp comments:

Hi Reigel, this is almost what I wanted thank-you. It displays the warning message only once, however, so if the user decides to keep adding more than 6 top level menu items, the warning is not displayed again for the 8th, 9th etc top level menu added. I would like it to display the warning every time the user adds another top level menu item, not just for the 7th added?

mattp comments:

Sorry having tested it again, it's 100% perfect so thank-you. Please ignore the comment above.