Display Author role in archive or author page

I want to display author role on archive and author page outside loop I found this code on stack overflow and it works fine within the loop

function get_author_role()
{
    global $authordata;

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

    return $author_role;
}

In template using below code

Read More
echo get_author_role()

But when I am adding this to archive and author page its giving me warning message called

Warning: array_shift() expects parameter 1 to be array, null given in

How to solve this?

Related posts

Leave a Reply

1 comment

  1. $authordata is not available before the first post is set up (before the first the_post();).

    But all the data you need are already there on an author archive: in get_queried_object().

    It is a WP_User Object on the author archive.

    print '<pre>' . htmlspecialchars( print_r( get_queried_object(), TRUE ) ) . '</pre>';
    

    Result:

    WP_User Object
    (
        [data] => stdClass Object
            (
                [ID] => 2
                [user_login] => toscho
                [user_pass] => $P$BO6.B4TIhxnKspIlxXHJCqa.M4I3v01
                [user_nicename] => toscho
                [user_email] => toscho@localhost.invalid
                [user_url] => 
                [user_registered] => 2011-12-25 15:20:12
                [user_activation_key] => 
                [user_status] => 0
                [display_name] => toscho
            )
    
        [ID] => 2
        [caps] => Array
            (
                [author] => 1
            )
    
        [cap_key] => test_capabilities
        [roles] => Array
            (
                [0] => author
            )
    
        [allcaps] => Array
            (
                [upload_files] => 1
                [edit_posts] => 1
                [edit_published_posts] => 1
                [publish_posts] => 1
                [read] => 1
                [level_2] => 1
                [level_1] => 1
                [level_0] => 1
                [delete_posts] => 1
                [delete_published_posts] => 1
                [author] => 1
            )
    
        [filter] => 
    )
    

    So this will print the current author’s first role:

    ! empty ( get_queried_object()->roles )
        and print ucfirst( get_queried_object()->roles[0] );