我们在使用 WordPress 的过程中,某些文章或页面有可能需要输出文章作者的相关信息,如作者 ID、昵称、描述等,这个时候我们就需要用到这个 WordPress 获取作者相关信息函数 get_the_author_meta(),今天我们就跟大家说一说这个函数的介绍及使用示例。
get_the_author_meta()函数介绍
检索(获取)当前帖子作者的相关信息。
get_the_author_meta( string $field = '', int|false $user_id = false )
参数:
- $field(string):(可选)要检索的作者字段,默认值:”。
- $user_id(int | false):(可选)作者(用户)标识 ID,默认值:false。
参数$field 有效值包括:
- admin_color
- aim
- comment_shortcuts
- description
- display_name
- first_name
- ID
- jabber
- last_name
- nickname
- plugins_last_view
- plugins_per_page
- rich_editing
- syntax_highlighting
- user_activation_key
- user_description
- user_email
- user_firstname
- user_lastname
- user_level
- user_login
- user_nicename
- user_pass
- user_registered
- user_status
- user_url
- yim
函数所在文件:wp-includes/author-template.php
function get_the_author_meta( $field = '', $user_id = false ) {
$original_user_id = $user_id;
if ( ! $user_id ) {
global $authordata;
$user_id = isset( $authordata->ID ) ? $authordata->ID : 0;
} else {
$authordata = get_userdata( $user_id );
}
if ( in_array( $field, array( 'login', 'pass', 'nicename', 'email', 'url', 'registered', 'activation_key', 'status' ), true ) ) {
$field = 'user_' . $field;
}
$value = isset( $authordata->$field ) ? $authordata->$field : '';
return apply_filters( "get_the_author_{$field}", $value, $user_id, $original_user_id );
}
get_the_author_meta()函数使用示例
示例:输出当前文章作者的描述并保持换行
<?php echo nl2br(get_the_author_meta('description')); ?>
示例:获取作者 ID
1、获取作者 ID 外部循环:
global $post;
$author_id = $post->post_author;
2、在循环中获取作者 ID:
$author_id = get_the_author_meta( 'ID' );
3、获取作者其他信息
//获取作者昵称
get_the_author_meta( 'nickname', $author_id );
//获取作者邮箱
get_the_author_meta( 'email', $author_id );
//获取作者网址
get_the_author_meta( 'url', $author_id );
//获取作者状态
get_the_author_meta( 'status', $author_id );
示例:获取用户 ID 为 25 的邮箱地址
get_the_author_meta( 'user_email', 25 );