• Hi everyone,

    I am trying to insert a php code into a membership page (after member had logged in).
    I would like this php code to display the current user’s user role name.
    Currently I have this code inserted:

    
    <?php $user_info = get_userdata(1);
          echo 'Your membership role is: ' . implode(', ', $user_info->roles) . "\n";
    ?>
    

    It works brilliantly to display the user role slug, but I would like my code to display the user role name.

    I have tried several codes, and been informed that this one should work:

    
    <?php
    function get_user_role($user_id) {
    	global $wp_roles;
    
    	$roles = array();
    	$user = new WP_User( $user_id );
    	if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
    	foreach ( $user->roles as $role )
    		$roles[] .= translate_user_role($wp_roles->roles[$role]['name']);
    	}
    	return implode(', ',$roles);
    } 
    

    However, having tried several examples several times, I have still not come up with a proper script to display the user role name, so I am still stuck with the user role slug.

    Help is much appreciated!

    Regards,
    kyrredyr

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator Steven Stern (sterndata)

    (@sterndata)

    Volunteer Forum Moderator

    <?php
    function get_user_role($user_id) {
    	global $wp_roles;
    
    	$roles = array();
    	$user = new WP_User( $user_id );
    	if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
    	foreach ( $user->roles as $role )
    		$roles[] .= translate_user_role($role['name']);
    	}
    	return implode(', ',$roles);
    } 
    Thread Starter kyrredyr

    (@kyrredyr)

    Hi!

    Thanks for your prompt reply! Just tried the code, and unfortunately it seems like it is not working – nothing showing up ??

    Moderator bcworkz

    (@bcworkz)

    Change Steve’s one line like so:
    $roles[] .= translate_user_role( $role );
    ($user->roles is a list of names, not role objects)

    This is a function declaration that returns a list of a user’s roles. You can place it in your child theme’s functions.php file (or early on on a template), then call it when you want to use it on a template like so:
    echo get_user_role( 7 );
    where 7 is the user’s ID of whom you want their roles listed.

    There is not a separate name and slug for roles, they are one and the same. Check out the WP_Role class declaration. See, name only, no slug.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Displaying user role name’ is closed to new replies.