0

I am trying to get my frontend to show the role of a logged-in user via Shortcode. I have the Shortcode functional (see below) but it displays the slug and not the real name in the frontend. This is a problem as the slugs are case insensitive and do not display any special characters. How do i get it to display the name rather than the slug?

Any help is greatly appreciated.

// [current_user_role]
function get_user_role() {
    global $current_user;
    $user_roles = $current_user->roles;
    $user_role = array_shift($user_roles);
    return $user_role;
}
add_shortcode('current_user_role', 'get_user_role');
1
  • Hi and welcome !
    – PhpDoe
    Oct 1, 2023 at 19:22

1 Answer 1

0

Based on what you wrote, you should use instead :

if ( ! is_admin() ) {
    function get_user_role() {
        global $wp_roles;
        $user = wp_get_current_user();
        $roles = ( array ) $user->roles;
        foreach ( $roles as $role ) {
            $user_role = '<p>' . $wp_roles->roles[ $role ]['name'] . '</p>';
        }
        return $user_role;
    }
    add_shortcode( 'display_user_role', 'get_user_role' );
}

It works pretty well on my install !

7
  • Awesome! As the page that the shortcode gets displayed is only visible to logged in users it is not needed to check if user is logged in. Can you adjust it so it looks like the initial snippet or could that bring any Problems in the future?
    – user235991
    Oct 1, 2023 at 19:23
  • 1
    Also it seems that your code displays a list on top of the page but not where the shortcode gets entered. Haw can I change that? Thank you so much
    – user235991
    Oct 1, 2023 at 19:30
  • I've modified the short code without the condition. Hmm, for you last comment, i don't see why it appears on the top, as on my install it appears exactly where I display it. Where exactly do you display the shortcode ?
    – PhpDoe
    Oct 1, 2023 at 19:37
  • It gets displayed above the woocommerce_my_account shortcode and shows a customer what status he has. Maybe it is because the output is a list and not only the primary role itself?
    – user235991
    Oct 1, 2023 at 19:43
  • Oh sorry, my mistake ! It's because a shortcode should not echo anything. Now it should work perfectly. Can you mark my answer if it solved your problem ?
    – PhpDoe
    Oct 1, 2023 at 19:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.