How to Default Craft 5 CP Sidebar to Collapsed

It's as easy as checking for and then setting a cookie in a custom module.


One of the new fea­tures in Craft CMS 5 con­trol pan­el is the col­lapsable side­bar. It’s a handy fea­ture that allows you to have more hor­i­zon­tal space while pub­lish­ing con­tent. Craft sets a cook­ie the first time you col­lapse the side­bar with a val­ue of collapsed. After that, it updates the cook­ie with the val­ue of expanded or collapsed depend­ing on the action you take. 

How­ev­er, I want­ed a way to make it the side­bar nav­i­ga­tion col­lapsed default, and Craft doesn’t yet allow that as a set­ting or preference.

Time to call up a cus­tom mod­ule and a lit­tle bit of PHP to set a cookie. 

If your project doesn’t already have a mod­ule, you’ll need to cre­ate. The eas­i­est way to do that is using Craft Gen­er­a­tor.

Once you have your mod­ule cre­at­ed, go the mod­ule file (mine is called sitemodule.php and add this code inside of Craft::$app->onInit() since we don’t need to run this code until Craft is ful­ly initialized:

$cookieName = 'Craft-' . Craft::$app->getSystemUid() . ':sidebar';

if (!Craft::$app->request->getRawCookies()->get($cookieName)) {
    $expiryTime = time() + 86400 * 365; // One year from now
    setcookie($cookieName, 'collapsed', $expiryTime, '/');

First, we set the cook­ie name we’ll check or cre­ate to the same cook­ie name that Craft 5 will set. After that, we check for the cook­ie; if it is not set, we set it with the val­ue of collapsed and a expi­ra­tion of a year from the time set. 

If the cook­ie does exist, then we don’t set any­thing because we don’t want to over­ride an expand­ed side­bar and make it col­lapsed. We’ll assume it is expand­ed for a rea­son and hon­or that.

To test the code, clear the cook­ie, if set, from your brows­er and reload the con­trol pan­el. Hel­lo, col­lapsed sidebar!