我正在开发我的第一个WP网站,需要在帖子旁边显示作者的角色.像"吉米|管理员"之类的东西.查看作者可用的元数据:http://codex.wordpress.org/Function_Reference/the_author_meta并没有给我一种方法来访问它.我确信有一个快速简单的方法来做到这一点,我只是不知道它!谢谢!
mai*_*o84 14
更新:将它放在functions.php文件中:
function get_author_role()
{
global $authordata;
$author_roles = $authordata->roles;
$author_role = array_shift($author_roles);
return $author_role;
}
Run Code Online (Sandbox Code Playgroud)
然后在你的Wordpress循环中调用它.所以:
<?php
if(have_posts()) : while(have_posts()) : the_post();
echo get_the_author().' | '.get_author_role();
endwhile;endif;
?>
Run Code Online (Sandbox Code Playgroud)
...将打印:'吉米| 管理员'
完整的答案:用户对象本身实际上存储了角色和其他有用的信息.如果您想要更多通用函数来检索任何给定用户的角色,只需使用此函数传入要定位的用户的ID:
function get_user_role($id)
{
$user = new WP_User($id);
return array_shift($user->roles);
}
Run Code Online (Sandbox Code Playgroud)
如果你想抓住一个给定帖子的作者,请这样称呼它:
<?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;
?>
Run Code Online (Sandbox Code Playgroud)
对最后评论的回应:
如果您需要在Wordpress循环之外获取数据(我想您正在尝试在存档和作者页面上执行此操作),您可以使用我的完整答案中的函数,如下所示:
global $post;
$aid = $post->post_author;
echo get_the_author_meta('user_nicename', $aid).' | '.get_user_role($aid);
Run Code Online (Sandbox Code Playgroud)
这将以"用户|角色"格式输出您想要的信息.
| 归档时间: |
|
| 查看次数: |
7010 次 |
| 最近记录: |