comment_author()
云策文档标注
概述
comment_author() 函数用于显示当前评论的作者名称。它接受一个可选的评论 ID 或 WP_Comment 对象作为参数,默认处理当前评论。
关键要点
- 参数 $comment_id 可选,可以是整数或 WP_Comment 对象,默认值为 0 表示当前评论。
- 如果评论未提供作者名称且未启用讨论选项中的“用户必须填写姓名和邮箱”,WordPress 会显示“Anonymous”。
- 函数内部使用 get_comment() 获取评论数据,并通过 get_comment_author() 检索作者名称。
- 输出前应用 'comment_author' 过滤器,允许开发者修改显示的评论作者名称。
- 自 WordPress 4.4.0 起,$comment_id 参数支持 WP_Comment 对象。
代码示例
function comment_author( $comment_id = 0 ) {
$comment = get_comment( $comment_id );
$comment_author = get_comment_author( $comment );
/**
* Filters the comment author's name for display.
*
* @since 1.2.0
* @since 4.1.0 The `$comment_id` parameter was added.
*
* @param string $comment_author The comment author's username.
* @param string $comment_id The comment ID as a numeric string.
*/
echo apply_filters( 'comment_author', $comment_author, $comment->comment_ID );
}注意事项
- 确保在评论循环或相关上下文中调用此函数,以避免未定义行为。
- 使用 'comment_author' 过滤器时,注意参数顺序和类型,以正确自定义输出。
原文内容
Displays the author of the current comment.
Parameters
$comment_idint|WP_Commentoptional-
WP_Comment or the ID of the comment for which to print the author.
Default current comment.
Source
function comment_author( $comment_id = 0 ) {
$comment = get_comment( $comment_id );
$comment_author = get_comment_author( $comment );
/**
* Filters the comment author's name for display.
*
* @since 1.2.0
* @since 4.1.0 The `$comment_id` parameter was added.
*
* @param string $comment_author The comment author's username.
* @param string $comment_id The comment ID as a numeric string.
*/
echo apply_filters( 'comment_author', $comment_author, $comment->comment_ID );
}
Hooks
- apply_filters( ‘comment_author’, string $comment_author, string $comment_id )
-
Filters the comment author’s name for display.
Changelog
| Version | Description |
|---|---|
| 4.4.0 | Added the ability for $comment_id to also accept a WP_Comment object. |
| 0.71 | Introduced. |
Skip to note 2 content
Codex
Basic Example
<div>Comment by :</div>