Creating menus based on login status

 

In this example, I will show you how to display a different menu for users based on their login status for the WordPress TwentyTen theme. This process can be adapted to any theme (and using the same principles, could be adapted to use anywhere on your WP site).

Note: There is an alternate (and easier) method of doing this posted here.  That post displays the method currently used on this site.

Some Prerequisites

This is primarily for those using WP-Members who have asked about showing different menu items based on a user’s login status; but the method described is not limited to use with the plug-in. This will work with any WordPress installation.

This post assumes that the reader is already familiar with creating menus through the WordPress admin panel. If not, you can familiarize yourself with this process via the WordPress Codex.

It is VERY important to note that you should not make the discussed edits to TwentyTen directly. You should be using a child theme for any changes, otherwise, when you upgrade WordPress or TwentyTen, your changes will be overwritten. A tutorial on creating child themes is not the purpose of this post. If you are not familiar with this process, begin with the WordPress Codex description of Child Themes.

The Process

First, create two menus. This is done in your WP admin panel under Appearance > Menus. For this example, I created on called “logged-in” and one called “logged-out”. It should be intuitive which is which.

For the “logged-in” menu, add the pages and content you want in the menu for users who are logged in. For the “logged-out” menu, put in the content to display if the user is not logged in.

To implement these menus, you will make a slight change to the header.php file for the TwentyTen theme. Look for the following line in this file:

<?php wp_nav_menu( array( 'container_class' =>; 'menu-header', 'theme_location' => 'primary' ) ); ?>

Replace that line with the following:

<?php
if( is_user_logged_in() ) {
     $menu = 'logged-in';
} else {
     $menu = 'logged-out';
}
wp_nav_menu( array( 'menu' => $menu, 'container_class' => 'menu-header', 'theme_location' => 'primary' ) );
?>;

Basically, we are just adding a parameter for wp_nav_menu to determine which menu to load. We are using a variable $menu that will provide the menu name depending on the user’s login status.

It’s that simple.

For a related discussion on how to display different elements in the Loop area of your theme, see this post: Blocking Content in a Custom Template.


Originally posted at http://butlerblog.com/2011/11/21/show-menu-based-on-wordpress-login-status/

Private

You do not have permission to view this forum.