Wordpress - How to limit wordpress menu depth in admin panel
The solution that I came up with:
/**
* Limit max menu depth in admin panel to 2
*/
function q242068_limit_depth( $hook ) {
if ( $hook != 'nav-menus.php' ) return;
// override default value right after 'nav-menu' JS
wp_add_inline_script( 'nav-menu', 'wpNavMenu.options.globalMaxDepth = 1;', 'after' );
}
add_action( 'admin_enqueue_scripts', 'q242068_limit_depth' );
Follow up on @jmarceli's and @squarecandy's great answers. Here is a solution that allows for:
- Easier scaling (set an object in the php action)
- Updates to the correct menu depth when the location checkboxes are changed
/**
* Limit max menu depth in admin panel
*/
function limit_admin_menu_depth($hook)
{
if ($hook != 'nav-menus.php') return;
wp_register_script('limit-admin-menu-depth', get_stylesheet_directory_uri() . '/js/admin/limit-menu-depth.js', array(), '1.0.0', true);
wp_localize_script(
'limit-admin-menu-depth',
'myMenuDepths',
array(
'primary' => 1, // <-- Set your menu location and max depth here
'footer' => 0 // <-- Add as many as you like
)
);
wp_enqueue_script('limit-admin-menu-depth');
}
add_action( 'admin_enqueue_scripts', 'limit_admin_menu_depth' );
js
/**
* Limit max menu depth in admin panel
* Expects wp_localize_script to have set an object of menu locations
* in the shape of { location: maxDepth, location2: maxDepth2 }
* e.g var menu-depths = {"primary":"1","footer":"0"};
*/
(function ($) {
// Get initial maximum menu depth, so that we may restore to it later.
var initialMaxDepth = wpNavMenu.options.globalMaxDepth;
function setMaxDepth() {
// Loop through each of the menu locations
$.each(myMenuDepths, function (location, maxDepth) {
if (
$('#locations-' + location).prop('checked') &&
maxDepth < wpNavMenu.options.globalMaxDepth
) {
// If this menu location is checked
// and if the max depth for this location is less than the current globalMaxDepth
// Then set globalMaxDepth to the max depth for this location
wpNavMenu.options.globalMaxDepth = maxDepth;
}
});
}
// Run the function once on document ready
setMaxDepth();
// Re-run the function if the menu location checkboxes are changed
$('.menu-theme-locations input').on('change', function () {
wpNavMenu.options.globalMaxDepth = initialMaxDepth;
setMaxDepth();
});
})(jQuery);