函数文档

get_comment_id_fields()

💡 云策文档标注

概述

get_comment_id_fields() 函数用于生成回复评论时所需的隐藏输入字段 HTML。它基于指定文章获取评论回复 ID,并可通过过滤器进行自定义。

关键要点

  • 函数返回隐藏输入 HTML,用于在评论回复中传递文章 ID 和回复目标评论 ID。
  • 参数 $post 可选,可以是文章 ID、WP_Post 对象或 null(默认为当前全局文章),用于指定相关文章。
  • 内部调用 _get_comment_reply_id() 从 $_GET['replytocom'] 获取回复目标评论 ID。
  • 输出可通过 'comment_id_fields' 过滤器钩子进行修改,允许开发者自定义 HTML 格式或添加额外数据。
  • 函数在 WordPress 3.0.0 中引入,6.2.0 版本更新了参数命名以支持 WP_Post 对象。

代码示例

function get_comment_id_fields( $post = null ) {
	$post = get_post( $post );
	if ( ! $post ) {
		return '';
	}

	$post_id     = $post->ID;
	$reply_to_id = _get_comment_reply_id( $post_id );

	$comment_id_fields  = "n";
	$comment_id_fields .= "n";

	/**
	 * Filters the returned comment ID fields.
	 *
	 * @since 3.0.0
	 *
	 * @param string $comment_id_fields The HTML-formatted hidden ID field comment elements.
	 * @param int    $post_id           The post ID.
	 * @param int    $reply_to_id       The ID of the comment being replied to.
	 */
	return apply_filters( 'comment_id_fields', $comment_id_fields, $post_id, $reply_to_id );
}

注意事项

  • 如果 $post 参数无效或文章不存在,函数返回空字符串,确保输出安全。
  • 此函数通常被 comment_id_fields() 和 comment_form() 调用,用于在评论表单中嵌入必要数据。
  • 开发者可以利用 'comment_id_fields' 过滤器调整输出,例如添加自定义字段或修改 HTML 结构。

📄 原文内容

Retrieves hidden input HTML for replying to comments.

Parameters

$postint|WP_Post|nulloptional
The post the comment is being displayed for.
Defaults to the current global post.

Default:null

Return

string Hidden input HTML for replying to comments.

Source

function get_comment_id_fields( $post = null ) {
	$post = get_post( $post );
	if ( ! $post ) {
		return '';
	}

	$post_id     = $post->ID;
	$reply_to_id = _get_comment_reply_id( $post_id );

	$comment_id_fields  = "<input type='hidden' name='comment_post_ID' value='$post_id' id='comment_post_ID' />n";
	$comment_id_fields .= "<input type='hidden' name='comment_parent' id='comment_parent' value='$reply_to_id' />n";

	/**
	 * Filters the returned comment ID fields.
	 *
	 * @since 3.0.0
	 *
	 * @param string $comment_id_fields The HTML-formatted hidden ID field comment elements.
	 * @param int    $post_id           The post ID.
	 * @param int    $reply_to_id       The ID of the comment being replied to.
	 */
	return apply_filters( 'comment_id_fields', $comment_id_fields, $post_id, $reply_to_id );
}

Hooks

apply_filters( ‘comment_id_fields’, string $comment_id_fields, int $post_id, int $reply_to_id )

Filters the returned comment ID fields.

Changelog

Version Description
6.2.0 Renamed $post_id to $post and added WP_Post support.
3.0.0 Introduced.