2

How to display user role on author page.

I have created my own role (group) so I want to display the user role on below the post and on author list.

I have tried this code but not working as its calling current_user and its showing current user role in all authors profile

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

    if ($user_role == 'administrator') {
        echo 'Administrator';
    } elseif ($user_role == 'editor') {
        echo 'Editor';
    } elseif ($user_role == 'author') {
        echo 'Author';
    } elseif ($user_role == 'contributor') {
        echo 'Contributor';
    } elseif ($user_role == 'subscriber') {
        echo 'Subscriber';
    } else {
        echo '<strong>' . $user_role . '</strong>';
    }
?>

How can I alter this code to display user actual role and not the current user role.

2 Answers 2

2

Change:

$user_roles = $current_user->roles;

with

$user = new WP_User( $user_id );
$user_roles = $user->roles;

and the $user_id should e the actual user id who's role you are trying to get.

Update,

Sorry i just read the author template part so try this:

//first get the current author whos page you are viewing
if(isset($_GET['author_name']))
        $curauth = get_user_by('slug', $author_name);
else
        $curauth = get_userdata(intval($author));
//then get the user object with roles
$user = new WP_User( $$curauth->ID );
$user_roles = $user->roles; 
....
4
  • its giving blank output. No error or not text Commented May 27, 2012 at 14:18
  • try var_dump($user); to see what your are getting
    – Bainternet
    Commented May 27, 2012 at 14:19
  • getting this output object(WP_User)#349 (7) { ["data"]=> NULL ["ID"]=> int(0) ["caps"]=> array(0) { } ["cap_key"]=> NULL ["roles"]=> array(0) { } ["allcaps"]=> array(0) { } ["filter"]=> NULL } I am using name of the role if you see in my first code not any id so can that cause the issue? Commented May 27, 2012 at 14:22
  • @pixelngrain i updated my answer
    – Bainternet
    Commented May 27, 2012 at 14:31
3

I assume you are trying to show the role of the post's Author and not the current user viewing the author page.

assuming you are inside the loop, do the following:

//get the post author's ID
$user_id = get_the_author_meta( 'ID' ); //assume we are in The Loop

$user_obj = get_userdata( $user_id );

if( !empty( $user_obj->roles ) ){
    foreach( $user_obj->roles as $role ){
        echo $role;
    }
}

or, if you only assign one role to each user/author, then you can do the following instead replacing the whole foreach block:

echo $user_obj->roles[0];

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.