2

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

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?

2
  • Any progress? Was my answer helpful? Do you still miss something?
    – fuxia
    Oct 6 '12 at 22:42
  • Unfortunately, this code didn't work so I had to found another solution. I will post here. Oct 7 '12 at 8:45
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] );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.