在wordpress中使用get_authors()获取作者列表时,需为每个作者显式传入其id参数调用get_the_author_meta(),否则无法读取job_title等自定义作者元数据。
在wordpress中使用get_authors()获取作者列表时,需为每个作者显式传入其id参数调用get_the_author_meta(),否则无法读取job_title等自定义作者元数据。
在构建WordPress作者归档页面(Author Archive Page)时,开发者常误以为get_authors()返回的作者对象已包含全部元数据(如头像、职位、社交媒体链接等)。实际上,该函数仅返回基础用户信息(如ID、display_name、user_email),所有作者元字段(author meta)必须通过get_the_author_meta()单独查询,并严格传入对应作者的$author->ID作为第二个参数。
以下是一个规范、可扩展的实现示例:
<?php // 获取所有具有发布权限的作者(按文章数降序)
$authors = get_users([
'role__in' => ['administrator', 'editor', 'author'],
'orderby' => 'post_count',
'order' => 'DESC',
'who' => 'authors'
]);
if (!empty($authors)) :
foreach ($authors as $author) :
// ✅ 正确:为每个作者单独获取元数据
$job_title = get_the_author_meta('job_title', $author->ID);
$bio = get_the_author_meta('description', $author->ID);
$avatar = get_avatar($author->ID, 80);
// 可选:检查元字段是否存在,避免空值输出
$job_title = !empty($job_title) ? esc_html($job_title) : '未填写职位';
?>
<div class="author-card">
= $avatar ?>
<h2>= esc_html($author->display_name) ?></h2>
<p class="job-title">= $job_title ?></p>
<?php if (!empty($bio)) : ?><div class="author-bio">= wp_kses_post($bio) ?></div>
<?php endif; ?>
</div>
<?php endforeach;
else :
echo '<p>暂无作者信息。';
endif;
?>
? 关键注意事项:
- get_authors() 已弃用(deprecated),自 WordPress 3.1 起推荐使用 get_users() 并配合 'who' => 'authors' 或角色筛选(如上例),以获得更灵活、安全且兼容未来的查询能力;
- get_the_author_meta() 的第二个参数($user_id)不可省略——若缺失,函数默认使用当前主循环中的作者(即单篇文章上下文),在归档页中将导致所有作者显示同一人的元数据或空值;
- 始终对输出内容执行转义(如 esc_html()、wp_kses_post())和空值校验,防止XSS风险与前端渲染异常;
- 若需展示头像,建议使用 get_avatar($author->ID, $size) 而非依赖 get_the_author_meta('avatar')(该meta键通常不存在,头像是核心功能,由get_avatar()统一管理)。
✅ 总结:作者元数据不是“附着”在作者对象上的属性,而是独立存储于wp_usermeta表中,必须通过user_id精准关联查询。将get_the_author_meta()调用置于循环内部、并显式传入$author->ID,是实现多作者元数据显示的唯一可靠方式。










