This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

Create a specific menu for logged in users

Here’s a way to add a specific menu for logged in users, this is useful if you’re building a membership site, where users need to login first but no longer need to see the login link after login and the menu can then be replaced with a users Account, Settings or Preferences menu.

So, first of all, we will need 2 menu locations.

One for logged out users to login, and one for users after they have logged in.

// Register Navigation Menus
function wpstx_logged_in_user_menu() {

	$locations = array(
		'logged-in-menu' => __( 'User Menu', 'wpstx_logged_in_user_menu' ),
		'logged-out-menu' => __( 'Login', 'wpstx_logged_in_user_menu' ),
	);
	register_nav_menus( $locations );

}
add_action( 'init', 'wpstx_logged_in_user_menu' );

Next, we need to create an action hook that renders the menu conditionally depending if the user is logged in or not. Here we will use PHP Ternary operator logic on the built-in WordPress function is_user_logged_in() to render the one menu or the other.

// Function with a conditional for logged in/out users
function wpstx_users_menu() {
    wp_nav_menu(
        array(
            'theme_location' => is_user_logged_in() ? 'logged-in-menu' : 'logged-out-menu'
        )
    );
}
// create an action hook for uses in your theme
// to render the menu simply add "do_action('wpstx_users_menu');" anywhere in your theme
add_action('wpstx_users_menu','wpstx_users_menu');

This action hook can then be used in your theme’s header/footer or wherever you want to put it to conditionally render the function...

// add this to one of your template files
do_action('wpstx_users_menu');

With this snippet running all you need to do now is go to:
Dashboard > Appearance > Menus
to create a couple of menus and allocate them to the relevant menu locations.

Create a menu for non-logged in users
Create a menu for logged in users
How the menu looks to users who are not logged in
How the menu looks to users who are logged in

@source https://github.com/eirichmond/wpstx-specific-menu-for-loggedin-users

About

A geek who likes to code and be nice ^_^

Leave a Reply

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

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