get_author_posts_url()
云策文档标注
概述
get_author_posts_url() 函数用于根据用户 ID 获取作者页面的 URL。它处理固定链接设置,并可通过 author_link 过滤器进行自定义。
关键要点
- 函数接受两个参数:必需的 $author_id(整数类型)和可选的 $author_nicename(字符串类型,默认为空)。
- 返回值为字符串类型的作者页面 URL。
- 内部逻辑根据 WP_Rewrite 的固定链接结构生成 URL,若未设置则使用查询字符串格式。
- 提供 author_link 过滤器,允许开发者修改生成的 URL。
- 函数未进行转义,使用时需注意安全处理。
代码示例
$author_id = get_post_field('post_author', get_the_ID());
$author_url = get_author_posts_url($author_id);
echo esc_url($author_url);注意事项
由于函数输出未转义,建议在输出时使用 esc_url() 等函数进行转义以确保安全。
原文内容
Retrieves the URL to the author page for the user with the ID provided.
Parameters
$author_idintrequired-
Author ID.
$author_nicenamestringoptional-
The author’s nicename (slug). Default empty.
Source
function get_author_posts_url( $author_id, $author_nicename = '' ) {
global $wp_rewrite;
$author_id = (int) $author_id;
$link = $wp_rewrite->get_author_permastruct();
if ( empty( $link ) ) {
$file = home_url( '/' );
$link = $file . '?author=' . $author_id;
} else {
if ( '' === $author_nicename ) {
$user = get_userdata( $author_id );
if ( ! empty( $user->user_nicename ) ) {
$author_nicename = $user->user_nicename;
}
}
$link = str_replace( '%author%', $author_nicename, $link );
$link = home_url( user_trailingslashit( $link ) );
}
/**
* Filters the URL to the author's page.
*
* @since 2.1.0
*
* @param string $link The URL to the author's page.
* @param int $author_id The author's ID.
* @param string $author_nicename The author's nice name.
*/
$link = apply_filters( 'author_link', $link, $author_id, $author_nicename );
return $link;
}
Hooks
- apply_filters( ‘author_link’, string $link, int $author_id, string $author_nicename )
-
Filters the URL to the author’s page.
Changelog
| Version | Description |
|---|---|
| 2.1.0 | Introduced. |
Skip to note 4 content
Jon (Kenshino)
Display the link of the author page for the author of the current post
<a href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>" title="<?php echo esc_attr( get_the_author() ); ?>"></a>Most get_ functions are not escaped and require escaping for safe usage.
Skip to note 5 content
Arafat Jamil
Link to the archive of posts created by the author of the current post.
$author_id = get_post_field( 'post_author', get_the_ID() ); <a href="<?php echo esc_url( get_author_posts_url( $author_id ) ); ?>"></a>Skip to note 6 content
Codex
Display the link of the author page for the author of the current post
<a href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) ); ?>"></a>