简体   繁体   中英

WordPress menu depending on user role

I have created 3 navigation menus to display depending on the role of the user, so I have one for the guest user, another for Wholesale and lastly a Hospitality navigation menu.

I am trying to display them depending on the role of the user when logged in. so the guest one when not logged in at all and then the other two when logged into to each of the accounts respectively. I have done the following argument:

        <?php
        if ( is_user_logged_in('administrator') ) {?>
           <?php wp_nav_menu( array( 'menu' => 'guest-menu' ) ); ?>
        <?php
        } else if ( is_user_logged_in('wholesale_customer') ) {?>
           <?php wp_nav_menu( array( 'menu' => 'wholesale-menu' ) ); ?>
        <?php
        } else if ( is_user_logged_in('hospitality_customer') ) {?>
           <?php wp_nav_menu( array( 'menu' => 'hospitality-menu' ) ); ?>
        <?php
        } else  {?>
           <?php wp_nav_menu( array( 'menu' => 'guest-menu' ) ); ?>
        <?php
        }
        ?>

I have created the Wholesale and Hospitality user accounts through a wholesale plugin I am using and the keys for the users are: wholesale_customer & hospitality_customer but no matter what it shows the guest menu? So my guess is that it either does not get past the first argument or it just skips to the end.

Try this,

$user = wp_get_current_user();

if ( in_array( 'wholesale_customer', (array) $user->roles ) {
    wp_nav_menu( array( 'menu' => 'wholesale-menu' ) );

} else if ( in_array( 'hospitality_customer', (array) $user->roles ) ) {
     wp_nav_menu( array( 'menu' => 'hospitality-menu' ) );

} else  {
     wp_nav_menu( array( 'menu' => 'guest-menu' ) );
}

With thanks to the guys above and for others looking for the answer please see who I come to achieve a working result:

        <?php

        global $current_user; 

        get_currentuserinfo();

        switch (true)  {
         case ( user_can( $current_user, "administrator") ):?>
           <?php wp_nav_menu( array( 'menu' => 'guest-menu' ) );
         break;
         case ( user_can( $current_user, "wholesale_customer") ):?>
           <?php wp_nav_menu( array( 'menu' => 'wholesale-menu' ) ); 
         break;
         case ( user_can( $current_user, "hospitality_customer") )?>
           <?php wp_nav_menu( array( 'menu' => 'hospitality-menu' ) ); 
         break;
          default:
          wp_nav_menu( array( 'menu' => 'guest-menu' ) );
          break;
        }

        ?>

UPDATE:

get_currentuserinfo() has been deprecated since version 4.5, now it is recommended to use wp_get_current_user instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM