I’d like to programmatically (either with js or php, but I imagine it’d simpler with js) hide the dashboard admin menu using the same functionality that is already built in.
All I want is, when the user clicks on a custom link in the dashboard the admin menu will collapse, so I have more screen space. Does anyone know how to do this?
I’ve been searching for a couple days and can only find how to remove the menu completely, which is not what I want. I could do that with a custom js script, however I’d rather just add an additional event handler to the current js function that hides the menu.
Add a javascript to all admin pages:
The javascript:
We want to catch all clicks inside the admin menu. If we catch a click inside the admin menu, we have to check if the admin menu is already folded. Now we have to check if the unfold button (uncollapse button) was clicked. This is a bit tricky, because if the admin menu is folded, the unfold button has no class or id. It is simply a
<div>
-element. But all others menu items are also<div>
-elements. So we can test if the clicked element has a class. If the clicked element has a class, it was not the unfold button and the menu should be folded.Now put all together: If the admin menu is not folded AND the clicked element is not a div element AND the clicked element has a class, then we expect it was not the unfold button that was clicked and the menu should be folded.
In this case we add the class
folded
to teh body element. Now we have to store that we have folded the admin menu. Because on the next page load the added class will be removed. We do this withsetUserSetting( 'mfold', 'f' )
.setUserSetting()
is a function fromwp-includes/js/utils.js
and store a value in the WordPress cookie.Adding to
setUserSetting()
discussion, WordPress cookies are how it sets the preference per user in their user profile. So if you’re like me and accidentally making something and happened by chance to save the setting to in the cookie then you get stuck with it saved “collapsed” you can reset all user preferences using the example below:Paste this into child theme functions.php file.
This sets collapse default:
This resets uncollapse default: