钩子文档

comments_pre_query

💡 云策文档标注

概述

comments_pre_query 是一个 WordPress 过滤器,用于在评论查询执行前拦截并自定义返回数据,从而绕过默认查询。开发者可以根据查询变量返回整数、数组或 WP_Comment 对象。

关键要点

  • 过滤器允许返回非空值以绕过 WordPress 的默认评论查询。
  • 返回类型取决于查询变量:当 $this->query_vars['count'] 设置时返回整数;当 'ids' === $this->query_vars['fields'] 时返回评论 ID 数组;否则返回 WP_Comment 对象数组。
  • 如果返回评论数据数组,它将被赋值给当前 WP_Comment_Query 实例的 comments 属性。
  • 建议需要分页信息的过滤函数设置 WP_Comment_Query 对象的 found_comments 和 max_num_pages 属性。

注意事项

如果 WP_Comment_Query 不执行数据库查询,它可能无法自动生成分页值,因此开发者应手动设置相关属性。


📄 原文内容

Filters the comments data before the query takes place.

Description

Return a non-null value to bypass WordPress’ default comment queries.

The expected return type from this filter depends on the value passed in the request query vars:

  • When $this->query_vars['count'] is set, the filter should return the comment count as an integer.
  • When 'ids' === $this->query_vars['fields'], the filter should return an array of comment IDs.
  • Otherwise the filter should return an array of WP_Comment objects.

Note that if the filter returns an array of comment data, it will be assigned to the comments property of the current WP_Comment_Query instance.

Filtering functions that require pagination information are encouraged to set the found_comments and max_num_pages properties of the WP_Comment_Query object, passed to the filter by reference. If WP_Comment_Query does not perform a database query, it will not have enough information to generate these values itself.

Parameters

$comment_dataarray|int|null
Return an array of comment data to short-circuit WP’s comment query, the comment count as an integer if $this->query_vars['count'] is set, or null to allow WP to run its normal queries.
$queryWP_Comment_Query
The WP_Comment_Query instance, passed by reference.

Source

$comment_data = apply_filters_ref_array( 'comments_pre_query', array( $comment_data, &$this ) );

Changelog

Version Description
5.6.0 The returned array of comment data is assigned to the comments property of the current WP_Comment_Query instance.
5.3.0 Introduced.