Showing menu items to logged in users only

UPDATE: I have now determined how to extend this to show menu items to ONLY guests. Something I’ve been looking at for a while. 

I have been searching for a simple way to show particular menu items to only logged in users. I know there are ways of achieving this in php by hardcoding your menu structure within the template for your site, but this involves delving into the source code (which I don’t like doing), and then makes the menu less dynamic to changes. That is, if you later add a page, you have to re-edit the code to have the menu updated…

Until now!

I found this the other day (credit reference below) and with a little CSS injection and associating a class with the menu item, we can have the same end-user effect.

Firstly you need to determine the name of the ID associated with your menu. What you are looking for is the name of the ID of the unordered list, or the div immediately prior to this, that contains your menu items. It will be some derivative of your primary menu’s name. View your source, grab this info and change “#nav” below to “#menu-MYMENUNAME”. It will be all lowercase.

Once you have that, now you need to add some code to your style sheet:

#nav li.logged-in-nav {
  display: none;
} 

body.logged-in #nav li.logged-in-nav {
  display: list-item;
}

logged-in-navThen, simply add the “logged-in-nav” class to the optional CSS Classes field for the menu item (as per the screen cap on the right).

It’s really that simple!

Now any menu items that have this class added to the CSS will only be visible to the end user if they are logged into the site.

If only I could make this work so that a particular menu item was ONLY visible to a guest! Now THAT is my next goal. Unfortunately there is no body class associated with users who aren’t logged in.

Reference: I originally found this snippet and give all credit to Bill Erickson at:
http://www.billerickson.net/customizing-wordpress-menus/#logged-in
Thanks Bill!

NB: There is one downside to this method. The end-user does not SEE the menu item, because the CSS “hides” it from them. It doesn’t altogether remove it from the page source and screen readers may in fact read the menu item, or anyone viewing the source will see these links — whether logged in or not. So unless you have the destination pages “controlled” in some other way, then maybe this method isn’t the best solution. However, for what I want, this is perfect.

This entry was posted in general. Bookmark the permalink.

19 Responses to Showing menu items to logged in users only

  1. Pingback: Guest only menu items | dav3 on wordpress

  2. Pingback: Showing menu items to logged in users only | dav3 on wordpress | DCS Enterprise

  3. Pingback: DCS Enterprise | Guest only menu items | dav3 on wordpress

Leave a Reply to Danny Cancel reply

Your email address will not be published. Required fields are marked *