get_comment_ID()
云策文档标注
概述
get_comment_ID() 函数用于获取当前评论的 ID,返回一个数字字符串。该函数内部调用 get_comment() 获取评论对象,并通过 apply_filters 钩子允许过滤返回值。
关键要点
- 函数返回当前评论的 ID,以数字字符串形式表示,若无评论则返回 '0'。
- 内部使用 get_comment() 函数获取评论对象,并检查 comment_ID 属性。
- 提供 apply_filters('get_comment_ID', $comment_id, $comment) 钩子,允许开发者过滤返回的评论 ID。
- 相关函数包括 comment_ID()(用于显示评论 ID)和 get_comment()(用于检索评论数据)。
- 自 WordPress 1.5.0 版本引入,保持向后兼容。
代码示例
// 使用 get_comment_ID() 获取评论 ID 作为锚点 ID
$comment_id = get_comment_ID();
echo '<div id="comment-' . esc_attr($comment_id) . '">Comment content</div>';
原文内容
Retrieves the comment ID of the current comment.
Source
function get_comment_ID() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
$comment = get_comment();
$comment_id = ! empty( $comment->comment_ID ) ? $comment->comment_ID : '0';
/**
* Filters the returned comment ID.
*
* @since 1.5.0
* @since 4.1.0 The `$comment` parameter was added.
*
* @param string $comment_id The current comment ID as a numeric string.
* @param WP_Comment $comment The comment object.
*/
return apply_filters( 'get_comment_ID', $comment_id, $comment ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
}
Hooks
- apply_filters( ‘get_comment_ID’, string $comment_id, WP_Comment $comment )
-
Filters the returned comment ID.
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 2 content
Steven Lin
Example migrated from Codex:
Uses the comment ID as an anchor id for a comment.
<div id="comment-<?php echo esc_attr( $comment_id ); ?>">Comment by : </div> <div class="comment-text"></div>