Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an author's role in Wordpress

Tags:

wordpress

i'm working on my first WP site and need to display an author's role next to their post. Something like "Jimmy | Administrator". Looking at the author metadata available: http://codex.wordpress.org/Function_Reference/the_author_meta doesn't give me a way to access that. I'm sure there's a quick easy way to do this and i just don't know it!! Thanks!

like image 855
panzhuli Avatar asked Dec 05 '22 16:12

panzhuli


1 Answers

UPDATE: Place this in your functions.php file:

function get_author_role()
{
    global $authordata;

    $author_roles = $authordata->roles;
    $author_role = array_shift($author_roles);

    return $author_role;
}

Then call this within your Wordpress Loop. So:

<?php
if(have_posts()) : while(have_posts()) : the_post();
    echo get_the_author().' | '.get_author_role();
endwhile;endif;
?>

...will print: 'Jimmy | Administrator'

COMPLETE ANSWER: The User Object itself actually stores roles, and other kinds of useful information. If you want more of a general function to retrieve the role of any given user, simply pass in the ID of the user you want to target with this function:

function get_user_role($id)
{
    $user = new WP_User($id);
    return array_shift($user->roles);
}

And if you want to grab the author of a given post, call it like so:

<?php
if(have_posts()) : while(have_posts()) : the_post();
    $aid = get_the_author_meta('ID');
    echo get_the_author().' | '.get_user_role($aid);
endwhile;endif;
?>

RESPONSE TO LAST COMMENT:

If you need to grab data outside of the Wordpress Loop (which I imagine you're trying to do on an Archive and Author page), you can use the function from my Complete answer like so:

global $post;
$aid = $post->post_author;
echo get_the_author_meta('user_nicename', $aid).' | '.get_user_role($aid);

That will output the information you want in your "user | role" format.

like image 73
maiorano84 Avatar answered Dec 07 '22 04:12

maiorano84