不同用户角色的不同菜单

时间:2014-03-06 14:39:17

标签: php wordpress if-statement wordpress-theming

我正在尝试根据用户角色显示两个不同的菜单。

我使用此代码(在functions.php中)设置了一个名为'clients'的新角色:

add_role( 'client', 'Client', array(
    'read' => true,
 ) 
);

我使用此代码有两个不同的菜单(在functions.php中):

function register_my_menus() {
  register_nav_menus(
    array(
  'client-navigation' => __( 'Client Navigation' ),
  'staff-navigation' => __( 'Staff Navigation' ),

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

这里是我试图用来调用客户端导航或员工导航的代码(在header.php中):

<?php
        if (current_user_can('client')){
            //menu for client role
             wp_nav_menu( array('theme-location' => 'client-navigation' ));

        }else{
            //default menu
             wp_nav_menu( array('theme-location' => 'staff-navigation' ));
        }
?>

我还尝试在wp_nav_menu之前添加'echo'并将theme-location更改为menu并使用菜单名称,但它始终显示staff-navigation菜单。

1 个答案:

答案 0 :(得分:2)

要使用current_user_can,您应该添加自己的custom capability

在没有这样做的情况下,当您正在寻找角色时,以下函数from here会完成这项工作:

function check_for_clients() {
    global $current_user;

    $user_roles = $current_user->roles;
    $user_role = array_shift($user_roles);

    return ($user_role == 'client');
}

然后在你的header.php文件中(注意你有一个typo in theme_location):

if ( check_for_clients() ){
     wp_nav_menu( array('theme_location' => 'client-navigation' ));

} else {
     wp_nav_menu( array('theme_location' => 'staff-navigation' ));
}