博客 / WordPress/ WordPress 如何调用作者头像、网站、邮箱及个人描述等信息

WordPress 如何调用作者头像、网站、邮箱及个人描述等信息

WordPress 如何调用作者头像、网站、邮箱及个人描述等信息

WordPress 作者信息调用方法

在 WordPress 主题开发中,经常需要调用文章作者的相关信息,例如名称、头像、网站、邮箱和个人描述等。以下介绍在文章循环内(如 single.php)和循环外(如作者存档页)调用作者信息的标准方法。

在文章循环内调用作者信息

while ( have_posts() ) : the_post(); 循环内,可以直接使用以下模板标签(Template Tags)来输出当前文章作者的信息:

<?php the_author(); ?>

常用作者信息模板标签列表:

  • the_author() – 显示文章作者的名称(显示名)。
  • the_author_meta( 'description' ) – 显示作者的个人描述(在“用户”资料中填写)。
  • the_author_meta( 'user_login' ) – 显示作者的登录名。
  • the_author_meta( 'first_name' ) – 显示作者的名字。
  • the_author_meta( 'last_name' ) – 显示作者的姓氏。
  • the_author_meta( 'nickname' ) – 显示作者的昵称。
  • the_author_meta( 'ID' ) – 显示作者的 ID。
  • the_author_meta( 'user_email' ) – 显示作者的电子邮箱。
  • the_author_meta( 'user_url' ) – 显示作者的网站地址。

注意: 原文中提到的 the_author_description, the_author_login 等函数在较新版本的 WordPress 中已不推荐使用或不存在。标准做法是统一使用 the_author_meta( $field ) 函数,其中 $field 是用户元字段名。

在循环外或指定作者调用信息

如果需要获取指定作者 ID 的信息,或在文章循环之外调用,应使用 get_the_author_meta( $field, $user_id ) 函数。此函数返回信息,而不是直接输出。

<?php
// 获取当前文章作者邮箱(循环内)
$author_email = get_the_author_meta( 'user_email' );
// 获取指定作者ID(例如 1)的网站
$author_site = get_the_author_meta( 'user_url', 1 );
?>

显示作者头像

使用 get_avatar() 函数可以显示作者的头像(Gravatar)。

<?php echo get_avatar( get_the_author_meta( 'ID' ), 96 ); ?>

参数 96 代表头像的尺寸(像素)。

列出所有作者(wp_list_authors)

要列出网站的所有作者及其文章数量,可以使用 wp_list_authors() 函数(原文中的 list_authors 已过时)。

<?php
$args = array(
    'orderby'      => 'name',
    'order'        => 'ASC',
    'show_count'   => true, // 是否显示文章数
    'hide_empty'   => false, // 是否隐藏未发表文章的作者
    'echo'         => true, // 直接输出还是返回HTML
);
wp_list_authors( $args );
?>

以上方法适用于现代 WordPress 版本(5.0+),兼容性更好,是当前主题开发的标准实践。

  1. avatar
    周小姐与瞄小姐

    WP越来越笨重了

    1. 还行吧,本博客没有开优化插件,没有使用缓存,没有rewrite,纯粹动态,只优化了主题,减少了点查询次数,目前还能接受

  2. avatar
    超級efly

    支持一下~你這個主題看起來有點老土 😛 歡迎訪問AREFLY.COM!

发表评论

您的邮箱不会公开。必填项已用 * 标注。