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.
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.
Share Improve this question asked May 27, 2012 at 13:57 pixelngrainpixelngrain 1,3901 gold badge23 silver badges50 bronze badges2 Answers
Reset to default 2Change:
$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;
....
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];