函数文档

get_comment()

💡 云策文档标注

概述

get_comment() 函数用于根据评论 ID 或评论对象检索评论数据。它支持多种输入类型和输出格式,并包含缓存和过滤机制。

关键要点

  • 函数接受 $comment 参数,可以是 WP_Comment 对象、字符串或整数,用于指定要检索的评论;若为空,则使用全局 $comment 变量。
  • 通过 $output 参数控制返回类型,可选 OBJECT(默认,返回 WP_Comment 对象)、ARRAY_A(关联数组)或 ARRAY_N(数字数组)。
  • 内部处理包括:检查全局变量、实例化 WP_Comment 对象、应用 get_comment 过滤器,并根据 $output 返回相应格式的数据。
  • 返回值为 WP_Comment 对象、数组或 null(如果评论不存在)。

代码示例

// 获取评论 ID 为 7 的评论作者名称
$comment = get_comment( 7 );
if ( $comment ) {
    echo $comment->comment_author;
}

// 使用 ARRAY_A 输出格式
$comment_array = get_comment( 7, ARRAY_A );
if ( $comment_array ) {
    echo $comment_array['comment_author'];
}

注意事项

  • 函数在检索评论后会触发 get_comment 过滤器,允许开发者修改返回的评论数据。
  • 如果评论不存在,函数返回 null,调用时应进行空值检查以避免错误。
  • 相关函数包括 WP_Comment::get_instance() 和 apply_filters(),用于内部实例化和过滤操作。

📄 原文内容

Retrieves comment data given a comment ID or comment object.

Description

If an object is passed then the comment data will be cached and then returned after being passed through a filter. If the comment is empty, then the global comment variable will be used, if it is set.

Parameters

$commentWP_Comment|string|intoptional
Comment to retrieve.

Default:null

$outputstringoptional
The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to a WP_Comment object, an associative array, or a numeric array, respectively.

Default:OBJECT

Return

WP_Comment|array|null Depends on $output value.

Source

function get_comment( $comment = null, $output = OBJECT ) {
	if ( empty( $comment ) && isset( $GLOBALS['comment'] ) ) {
		$comment = $GLOBALS['comment'];
	}

	if ( $comment instanceof WP_Comment ) {
		$_comment = $comment;
	} elseif ( is_object( $comment ) ) {
		$_comment = new WP_Comment( $comment );
	} else {
		$_comment = WP_Comment::get_instance( $comment );
	}

	if ( ! $_comment ) {
		return null;
	}

	/**
	 * Fires after a comment is retrieved.
	 *
	 * @since 2.3.0
	 *
	 * @param WP_Comment $_comment Comment data.
	 */
	$_comment = apply_filters( 'get_comment', $_comment );

	if ( OBJECT === $output ) {
		return $_comment;
	} elseif ( ARRAY_A === $output ) {
		return $_comment->to_array();
	} elseif ( ARRAY_N === $output ) {
		return array_values( $_comment->to_array() );
	}
	return $_comment;
}

Hooks

apply_filters( ‘get_comment’, WP_Comment $_comment )

Fires after a comment is retrieved.

Changelog

Version Description
2.0.0 Introduced.

User Contributed Notes