A while back I found a rather useful function for limiting the menu depth in the admin panel to 1-deep.
https://wordpress.stackexchange.com/a/377002
I just put the jquery in ./assets/js/limit-menu-depth.js and the accompany code in functions.php.
Now, I’m not sure how to implement this in Sage 10 and even less sure what would be the best practice.
I have jquery code, I want it to load only while logged into the admin panel only. How/where does this fit into webpack.mix.js? Also how would I rewrite this code in ./app/setup.php?
Any help would be greatly appreciated.
For convenience that code is:
/**
* 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' );
and the 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);