函数文档

get_comment_to_edit()

💡 云策文档标注

概述

get_comment_to_edit() 函数基于评论 ID 返回一个 WP_Comment 对象,用于编辑评论时处理内容。它通过 get_comment() 获取评论,并对评论内容、作者信息等进行格式化和过滤。

关键要点

  • 函数接受一个必需的整数参数 $id,表示要检索的评论 ID。
  • 返回 WP_Comment 对象(如果找到)或 false(如果失败)。
  • 内部使用 get_comment() 获取评论,并确保 comment_ID 和 comment_post_ID 为整数类型。
  • 对 comment_content、comment_author、comment_author_email 和 comment_author_url 应用 format_to_edit() 进行格式化。
  • 通过 apply_filters() 调用 'comment_edit_pre' 钩子过滤评论内容,允许开发者自定义处理。
  • 使用 esc_url() 清理 comment_author_url 以确保 URL 安全。

代码示例

function get_comment_to_edit( $id ) {
    $comment = get_comment( $id );
    if ( ! $comment ) {
        return false;
    }

    $comment->comment_ID      = (int) $comment->comment_ID;
    $comment->comment_post_ID = (int) $comment->comment_post_ID;

    $comment->comment_content = format_to_edit( $comment->comment_content );
    /**
     * Filters the comment content before editing.
     *
     * @since 2.0.0
     *
     * @param string $comment_content Comment content.
     */
    $comment->comment_content = apply_filters( 'comment_edit_pre', $comment->comment_content );

    $comment->comment_author       = format_to_edit( $comment->comment_author );
    $comment->comment_author_email = format_to_edit( $comment->comment_author_email );
    $comment->comment_author_url   = format_to_edit( $comment->comment_author_url );
    $comment->comment_author_url   = esc_url( $comment->comment_author_url );

    return $comment;
}

注意事项

  • 函数在 WordPress 2.0.0 版本中引入,是核心功能的一部分。
  • 相关函数包括 format_to_edit()、esc_url()、apply_filters() 和 get_comment(),用于辅助处理和格式化。
  • 确保传入的 $id 参数是有效的评论 ID,否则可能返回 false。
  • 通过 'comment_edit_pre' 钩子,开发者可以修改评论内容在编辑前的状态。

📄 原文内容

Returns a WP_Comment object based on comment ID.

Parameters

$idintrequired
ID of comment to retrieve.

Return

WP_Comment|false Comment if found. False on failure.

Source

function get_comment_to_edit( $id ) {
	$comment = get_comment( $id );
	if ( ! $comment ) {
		return false;
	}

	$comment->comment_ID      = (int) $comment->comment_ID;
	$comment->comment_post_ID = (int) $comment->comment_post_ID;

	$comment->comment_content = format_to_edit( $comment->comment_content );
	/**
	 * Filters the comment content before editing.
	 *
	 * @since 2.0.0
	 *
	 * @param string $comment_content Comment content.
	 */
	$comment->comment_content = apply_filters( 'comment_edit_pre', $comment->comment_content );

	$comment->comment_author       = format_to_edit( $comment->comment_author );
	$comment->comment_author_email = format_to_edit( $comment->comment_author_email );
	$comment->comment_author_url   = format_to_edit( $comment->comment_author_url );
	$comment->comment_author_url   = esc_url( $comment->comment_author_url );

	return $comment;
}

Hooks

apply_filters( ‘comment_edit_pre’, string $comment_content )

Filters the comment content before editing.

Changelog

Version Description
2.0.0 Introduced.