在 Wordpress 中获取作者的角色 [英] Getting an author's role in Wordpress

查看:33
本文介绍了在 Wordpress 中获取作者的角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的第一个 WP 网站上工作,需要在他们的帖子旁边显示作者的角色.类似于吉米|管理员".查看可用的作者元数据:http://codex.wordpress.org/Function_Reference/the_author_meta不给我一个方法来访问它.我相信有一种快速简单的方法可以做到这一点,我只是不知道!!谢谢!

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!

推荐答案

更新: 把它放在你的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.

这篇关于在 Wordpress 中获取作者的角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆