Set WordPress menus based on logged in status

How do I set my WordPress Menu to be different for guests and logged in users for WordPress?
I’m sure there is a plugin to do this, but if you believe that less is more this quicky will let you alter the main navigation menu from your theme. Your best bet is to use a child theme so that your changes will persist after theme updates. This is more a quick and dirty guide to get you started.

Step 1: Create the menus

Create 2 menus under Appearance -> Menus call them logged-in and logged-out
Fill the logged-in menu with items that you want members to see and the logged-out menu with public items.

Step 2: Alter the header.php for your theme

It should be said that these pages will still be visible to users guessing the URL’s to these pages.
To properly secure your pages you should either mark them private or password protect them or use User Access Manager

Having said that, the check is relatively simple: you can check for is_user_logged_in() and switch the menu around as required..
If you’re a programmer (in any language) you will probably understand what is going on, still I’ll take this step by step.
Let’s take Twenty Twelve as an example, you will need to find the code where the navigation menu is showed. In TwentyTwelve it is this line:

<?php wp_nav_menu( array( ‘theme_location’ => ‘primary’, ‘menu_class’ => ‘nav-menu’ ) ); ?>

theme_location refers to the configuration option in your theme (under Appearance -> Menus )
menu_class specifies the correct CSS class to be used when outputting your menu.
There are many more options, all of which are explained on this Codex page

Should you for example want to only show the menu to logged in users you can change it to:

<?php
if( is_user_logged_in() ) {
    <?php wp_nav_menu( array( ‘theme_location’ => ‘primary’, ‘menu_class’ => ‘nav-menu’ ) ); ?>
}

?>

Read this as “if user is logged in, execute the following.

Or maybe you want to show the menu named “logged-out” to all guests?

<?php
if( is_user_logged_in() ) {
    <?php wp_nav_menu( array( ‘theme_location’ => ‘primary’, ‘menu_class’ => ‘nav-menu’ ) ); ?>
}

    <?php wp_nav_menu( array( ‘menu’=>’logged-out’,’theme_location’ => ‘primary’, ‘menu_class’ => ‘nav-menu’ ) ); ?>

?>

menu basically does as you expect it to do, it loads the menu with the specified name (so you need to define it under Appearance -> Menus)

Now that you have seen some simple code, you might be interested in what else you can do! Just be sure to always make backups of your site, or better yet, use a separate site to test changes.

Leave a Reply