获得作者在Wordpress中的角色

时间:2012-05-07 21:12:38

标签: wordpress

我正在开发我的第一个WP网站,需要在帖子旁边显示作者的角色。像“吉米|管理员”之类的东西。查看可用的作者元数据:http://codex.wordpress.org/Function_Reference/the_author_meta并没有为我提供访问该元数据的方法。我确信有一个快速简单的方法来做到这一点,我只是不知道它!谢谢!

1 个答案:

答案 0 :(得分:12)

更新:将其放在您的functions.php文件中:

function get_author_role()
{
    global $authordata;

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

    return $author_role;
}

然后在Wordpress循环中调用它。所以:

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

...将打印:'吉米|管理员

完整的答案:用户对象本身实际上存储了角色和其他有用的信息。如果您想要更多通用函数来检索任何给定用户的角色,只需使用此函数传入您要定位的用户的ID:

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

如果你想抓住某个帖子的作者,可以这样称呼它:

<?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;
?>

对最后评论的回应:

如果您需要获取Wordpress循环之外的数据(我想您正在尝试在存档和作者页面上执行此操作),您可以使用我的完整答案中的函数,如下所示:

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

这将以“用户|角色”格式输出您想要的信息。