Skip to main content

Create two separate menu items for logged in and logged out users for WordPress

We can place two separate menu items for same position in WordPress. That means, if a user logged into the website, the user will see the available menus for logged in users. When the user log out from the website, he/she will se different menu which is for all guests.

To do that, simply create two menu from WordPress dashboard. It could contain any name of your choice. For example, the name of the menus could be "for logged in users" and "for logged out users".

Then, you have to declare the menu locations, for example: 

register_nav_menus( array(
'loggedin' => esc_html__( 'Logged In Menu', 'theme_name' ),
'loggedout' => esc_html__( 'Logged Out Menu', 'theme_name' ),
) );

This will add the options on menus page. Next, after assigning the menus to the respective menu locations, we have to show the menu in the theme: 

$args = array(
                        'theme_location' => 'loggedin',
                  // other arguments for nav goes here
              );
wp_nav_menu($args); 

And of course, we have to wrap this code in an if statement because we have to check the user is logged in or not. Simply add 

if (is_user_logged_in()) 

That's pretty much it. Now you can see different navigation for logged in users and guest users.

Thanks!

Comments

Popular posts from this blog

Set WordPress custom excerpt from Rank Math SEO plugin

  Sometimes, we need to set different excerpts for showing posts on the blog page. In this post, we are going to share a piece of code that works perfectly to change a posts' excerpt programmatically.  function rankmath_post_excerpt(){         $id = get_the_ID();         $post_type = get_post_type( get_the_ID() );         if ($post_type == 'post') {             $meta_description = get_post_meta($id,'rank_math_description',true);             return $meta_description;          }else{             return;         }          } function check_for_rankmath_activation(){     if ( is_plugin_active( 'seo-by-rank-math/rank-math.php' ) ){         add_filter('get_the_excerpt', 'rankmath_post_excerpt' );         add_filter('t...

Hide a product from WooCommerce main shop page

 function custom_pre_get_posts_query( $q ) {     $tax_query = (array) $q->get( 'tax_query' );     $tax_query[] = array(            'taxonomy' => 'product_cat',            'field' => 'slug',            'terms' => array( 'buster' ), // Don't display products in the clothing category on the shop page.            'operator' => 'NOT IN'     );     if(is_shop()){     $q->set( 'tax_query', $tax_query );   }else{     return;   }      } add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' );