函数文档

separate_comments()

💡 云策文档标注

概述

separate_comments() 函数用于将评论数组按评论类型(comment_type)进行分组,返回一个以评论类型为键的数组。它支持标准评论、trackback、pingback 和 pings 类型。

关键要点

  • 参数:接受一个必需的 WP_Comment[] 数组 $comments。
  • 返回值:返回一个数组,键为评论类型(如 'comment'、'trackback'、'pingback'、'pings'),值为对应类型的评论数组。
  • 功能:遍历评论数组,根据每个评论的 comment_type 属性进行分类,若类型为空则默认为 'comment',同时将 trackback 和 pingback 类型评论也添加到 'pings' 键中。
  • 相关函数:与 wp_list_comments() 和 comments_template() 相关,用于评论显示和模板加载。
  • 版本历史:自 WordPress 2.7.0 版本引入。

代码示例

function separate_comments( &$comments ) {
    $comments_by_type = array(
        'comment'   => array(),
        'trackback' => array(),
        'pingback'  => array(),
        'pings'     => array(),
    );

    $count = count( $comments );

    for ( $i = 0; $i < $count; $i++ ) {
        $type = $comments[$i]->comment_type;

        if ( empty( $type ) ) {
            $type = 'comment';
        }

        $comments_by_type[$type][] = &$comments[$i];

        if ( 'trackback' === $type || 'pingback' === $type ) {
            $comments_by_type['pings'][] = &$comments[$i];
        }
    }

    return $comments_by_type;
}

📄 原文内容

Separates an array of comments into an array keyed by comment_type.

Parameters

$commentsWP_Comment[]required
Array of comments.

Return

array<string, WP_Comment[]> Array of comments keyed by comment type.

Source

function separate_comments( &$comments ) {
	$comments_by_type = array(
		'comment'   => array(),
		'trackback' => array(),
		'pingback'  => array(),
		'pings'     => array(),
	);

	$count = count( $comments );

	for ( $i = 0; $i < $count; $i++ ) {
		$type = $comments[ $i ]->comment_type;

		if ( empty( $type ) ) {
			$type = 'comment';
		}

		$comments_by_type[ $type ][] = &$comments[ $i ];

		if ( 'trackback' === $type || 'pingback' === $type ) {
			$comments_by_type['pings'][] = &$comments[ $i ];
		}
	}

	return $comments_by_type;
}

Changelog

Version Description
2.7.0 Introduced.