且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Wordpress 中获取作者的角色

更新时间:2023-11-30 15:08:46

更新: 把它放在你的functions.php 文件中:

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

然后在您的 Wordpress 循环中调用它.所以:

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

...将打印:'Jimmy |管理员

...will print: 'Jimmy | Administrator'

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

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

对最后一条评论的回应:

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

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.