How to Add a Login/Logout Link to WordPress Menus

In my last post, I talked about how to add a custom meta box with a custom link to WordPress navigation menus. Several times, I mentioned how I needed to add a specific class to that link for WishList Login 2.0, so that I could find that link later and do stuff with it.

This is the part where we “do stuff” with that link. Specifically, we’re going to hook into the navigation menu before it displays, find our link and change its display based on the current user’s login status. Here’s what it looks like:

Adding a Login/Logout Link

So, if they’re logged in, we’re going to change it to a logout link. If they’re not logged, then we’ll leave it alone. Here’s the code to do that:

Here’s a run-down of what’s happening:

  1. We’re hooking in using the wp_nav_menu_objects filter.
  2. If the user is logged out, we just return the link as it is since by default it’s a login link.
  3. If the user is logged in, we then loop through the items and search the “classes” array element for our class.
  4. If the class exists in an item object, then we alter the “title” and “url” of that link and we unset our target class from the object.
  5. Then, we simply return the new objects array.

There’s definitely some customization and abstraction you could do with this:

1. Edit only the menu for a certain theme location. You’ll notice in the hook, I have 2 arguments being sent to the callback function, but I’m only actually using the first one. That’s to show you that there are actually 2 arguments available. The second one is the $args array which will contain information about that menu… including the theme location.

You would simply run a check on that array to see if the current theme location is the one you want to edit. This is especially important if you don’t want to touch widget menus at all… since, the Custom Menu widget uses the same back-end functionality as regular menus.

In our case, we wanted to hijack every instance of a link that contained our special class… even in a widget… so, we didn’t run any such check.

2. Abstract the target class. In our function, the target class we search for is hard-coded. In this instance, it’s fine because there’s no reason to have an option to change that class. You may have a scenario where it does make sense to allow users to change that class. In this case, you’d want to abstract that out by creating an admin option. You could then use get_option() to retrieve the target class and alter your menu accordingly.

So, that’s it. It’s a pretty straight-forward way to hook in and alter navigation menus how you’d like. And, IMHO, a hell of a lot easier than dealing with wp_nav_menu_items() and futzing with parsing HTML, and so on.

Join 7,700 Other Freelancers Who've Built Thriving Freelance Businesses

Over 7,700 other freelancers have started thriving freelance businesses using the information on this blog. Are you next? Subscribe below to get notified whenever a new article is posted and create your own success story:

You might also like

Facebook
Twitter
LinkedIn
Reddit
Pinterest
John Morris

JOHN MORRIS

I’m a 15-year veteran of freelance web development. I’ve worked with bestselling authors and average Joe’s next door. These days, I focus on helping other freelancers build their freelance business and their lifestyles.

This Post Has 16 Comments

  1. Nelson

    Yet ANOTHER awesome snippet–

    Thanks again!

  2. Dale

    The first part, adding a custom metabox, works great!
    This part results in a full white screen for me.
    I'm stumped.

    1. John Morris

      That is probably because I ported this from the actual plugin and didn't really test the actual code much. And, I was missing a parentheses around if ( !class_exists() ). I've updated the gist. Give it a try now.

      1. Dale

        Thanks John!

  3. Dale

    WOW!
    And here I was looking for blank spaces in the code.
    It works perfectly now.
    Thanks John.

  4. Dave

    But WHERE do I put this code????? Every site on the Internet has stuff liek this, but noone actually tells you what to do with the code????

    1. John Morris

      In a plugin or your theme's functions.php file.

  5. Hamish

    This rocks! Many thanks for sharing.
    Works a treat and I learnt some stuff too. All good.

  6. geomagas

    To make your plugin support custom links in navigation menus, THIS is the place to start.
    Along with the first part mentioned, of course!

    Really John, thanks a million!

  7. Saskia Beeldman

    I am trying to add some custom menu items with dynamic links to the menu meta box, so it is easy to add an dynamic link for non coders.
    Your code (in the former blog) was what I was looking for, but if I log in with another user it is displaying my link so it is not dynamic. I hoped this blog would solve my problem but is not doing anything and I can’t figure out why.

    I am pulling my hear out by now and really don’t know where to look for a solution.

    Could you help me please!

    1. John Morris

      @saskiabeeldman:disqus I’d need to see your code. If you can post it in something like pastebin I can take a look.

      1. Saskia Beeldman

        Hi John, i am pretty new to Disqus and just saw your reply. I aspected to get an email when a comment was made, but i didn’t. Sorry for the late reply and thanks you where willing to help me. I got it working but not in the way I hoped, for now the issue is solved, thanks again!

        1. John Morris

          Yeah, does the same to me sometimes. I don’t see every comment either. At least it’s working now I guess.

  8. san

    Why dont you make a plugin for this. it is super awsome

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Join 7,700 Other Freelancers Who've Built Thriving Freelance Businesses

Over 7,700 other freelancers have started thriving freelance businesses using the information on this blog. Are you next? Subscribe below to get notified whenever a new article is posted and create your own success story:

Success Stories

Ready to add your name here?

Tim Covello

Tim Covello

75 SEO and website clients now. My income went from sub zero to over 6K just last month. Tracking 10K for next month. Seriously, you changed my life.

Michael Phoenix

Michael Phoenix

By the way, just hit 95K for the year. I can’t thank you enough for everything you’ve taught me. You’ve changed my life. Thank you!

Stephanie Korski

Stephanie Korski

I started this 3 days ago, following John’s suggestions, and I gained the Upwork Rising Talent badge in less than 2 days. I have a call with my first potential client tomorrow. Thanks, John!

Jithin Veedu

Jithin Veedu

John is the man! I followed his steps and I am flooded with interviews in a week. I got into two Talent clouds. The very next day, I got an invitation from the talent specialists from Upwork and a lot more. I wanna shout out, he is the best in this. Thanks John for helping me out!

Divyendra Singh Jadoun

Divyendra Singh Jadoun

After viewing John’s course, I made an Upwork account and it got approved the same day. Amazingly, I got my first job the very same day, I couldn’t believe it, I thought maybe I got it by coincidence. Anyways I completed the job and received my first earnings. Then, after two days, I got another job and within a week I got 3 jobs and completed them successfully. All the things he says seem to be minute but have a very great impact on your freelancing career.

Sarah Mui

Sarah Mui

I’ve been in an existential crisis for the last week about what the heck I’m doing as a business owner. Even though I’ve been a business for about a year, I’m constantly trying to think of how to prune and refine services. This was very personable and enjoyable to watch. Usually, business courses like this are dry and hard to get through…. repeating the same things over and over again. This was a breath of fresh air. THANK YOU.

Waqas Abdul Majeed

Waqas Abdul Majeed

I’ve definitely learnt so much in 2.5 hours than I’d learn watching different videos online on Youtube and reading tons of articles on the web. John has a natural way of teaching, where he is passionately diving in the topics and he makes it very easy to grasp — someone who wants you to really start running your business well by learning about the right tools and implement them in your online business. I will definitely share with many of the people I know who have been struggling for so long, I did find my answers and I’m sure will do too.

Scott Plude

Scott Plude

I have been following John Morris for several years now. His instruction ranges from beginner to advanced, to CEO-level guidance. I have referred friends and clients to John, and have encouraged my own daughter to pay attention to what he says. All of his teachings create wealth for me (and happiness for my clients!) I can’t speak highly enough about John, his name is well known in my home.

Sukh Plaha

John is a fantastic and patient tutor, who is not just able to share knowledge and communicate it very effectively – but able to support one in applying it. However, I believe that John has a very rare ability to go further than just imparting knowledge and showing one how to apply it. He is able to innately provoke one’s curiosity when explaining and demonstrating concepts, to the extent that one can explore and unravel their own learning journey. Thanks very much John!

Mohamed Misrab

Misrab Mohamed

John has been the most important person in my freelance career ever since I started. Without him, I would have taken 10 or 20 years more to reach the position I am at now (Level 2 seller on Fiverr and Top Rated on Upwork).

Join 7,700 Other Freelancers Who've Built Thriving Freelance Businesses

Over 7,700 other freelancers have started thriving freelance businesses using the information on this blog. Are you next? Subscribe below to get notified whenever a new article is posted and create your own success story: