diff --git a/src/wp-includes/class-wp-comment-query.php b/src/wp-includes/class-wp-comment-query.php index c04584b9d1..f8836ca80a 100644 --- a/src/wp-includes/class-wp-comment-query.php +++ b/src/wp-includes/class-wp-comment-query.php @@ -394,7 +394,17 @@ class WP_Comment_Query { * 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. + * * @since 5.3.0 + * @since 5.6.0 The returned array of comment data is assigned to the `comments` property + * of the current WP_Comment_Query instance. * * @param array|int|null $comment_data 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, @@ -404,6 +414,10 @@ class WP_Comment_Query { $comment_data = apply_filters_ref_array( 'comments_pre_query', array( $comment_data, &$this ) ); if ( null !== $comment_data ) { + if ( is_array( $comment_data ) && ! $this->query_vars['count'] ) { + $this->comments = $comment_data; + } + return $comment_data; } diff --git a/tests/phpunit/tests/comment/query.php b/tests/phpunit/tests/comment/query.php index 012284eca6..9dab4adc46 100644 --- a/tests/phpunit/tests/comment/query.php +++ b/tests/phpunit/tests/comment/query.php @@ -4916,4 +4916,33 @@ class Tests_Comment_Query extends WP_UnitTestCase { return array( 555 ); } + + /** + * @ticket 50521 + */ + public function test_comments_pre_query_filter_should_set_comments_property() { + add_filter( 'comments_pre_query', array( __CLASS__, 'filter_comments_pre_query_and_set_comments' ), 10, 2 ); + + $q = new WP_Comment_Query(); + $results = $q->query( array() ); + + remove_filter( 'comments_pre_query', array( __CLASS__, 'filter_comments_pre_query_and_set_comments' ), 10, 2 ); + + // Make sure the comments property is the same as the results. + $this->assertSame( $results, $q->comments ); + + // Make sure the comment type is `foobar`. + $this->assertSame( 'foobar', $q->comments[0]->comment_type ); + } + + public static function filter_comments_pre_query_and_set_comments( $comments, $query ) { + $c = self::factory()->comment->create( + array( + 'comment_type' => 'foobar', + 'comment_approved' => '1', + ) + ); + + return array( get_comment( $c ) ); + } }