From 10b611b0c3081428d7f67c14824072e263d33116 Mon Sep 17 00:00:00 2001 From: Boone Gorges Date: Thu, 20 Nov 2014 01:51:38 +0000 Subject: [PATCH] Return an empty array from `get_approved_comments()` when `$post_id` is empty. This behavior was broken when moving the internals to `WP_Comment_Query` in [30098]. As a result, `get_approved_comments( 0 )` was fetching *all* approved comments, causing performance issues. Props dd32. Fixes #30412. git-svn-id: https://develop.svn.wordpress.org/trunk@30402 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/comment.php | 6 +++++- tests/phpunit/tests/comment.php | 12 ++++++++++++ tests/phpunit/tests/comment/query.php | 12 ++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/comment.php b/src/wp-includes/comment.php index a3e4ac1b4b..5d5689b9df 100644 --- a/src/wp-includes/comment.php +++ b/src/wp-includes/comment.php @@ -136,7 +136,11 @@ function check_comment($author, $email, $url, $comment, $user_ip, $user_agent, $ * @return int|array $comments The approved comments, or number of comments if `$count` * argument is true. */ -function get_approved_comments( $post_id = 0, $args = array() ) { +function get_approved_comments( $post_id, $args = array() ) { + if ( ! $post_id ) { + return array(); + } + $defaults = array( 'status' => 1, 'post_id' => $post_id, diff --git a/tests/phpunit/tests/comment.php b/tests/phpunit/tests/comment.php index bd24396068..6271696201 100644 --- a/tests/phpunit/tests/comment.php +++ b/tests/phpunit/tests/comment.php @@ -30,4 +30,16 @@ class Tests_Comment extends WP_UnitTestCase { // all comments types will be returned $this->assertEquals( array( $ca1, $ca2, $c2, $c3, $c4, $c5 ), wp_list_pluck( $found, 'comment_ID' ) ); } + + /** + * @ticket 30412 + */ + public function test_get_approved_comments_with_post_id_0_should_return_empty_array() { + $p = $this->factory->post->create(); + $ca1 = $this->factory->comment->create( array( 'comment_post_ID' => $p, 'comment_approved' => '1' ) ); + + $found = get_approved_comments( 0 ); + + $this->assertSame( array(), $found ); + } } diff --git a/tests/phpunit/tests/comment/query.php b/tests/phpunit/tests/comment/query.php index 77be42c4d7..dbdcf6aa58 100644 --- a/tests/phpunit/tests/comment/query.php +++ b/tests/phpunit/tests/comment/query.php @@ -30,6 +30,18 @@ class Tests_Comment_Query extends WP_UnitTestCase { $this->assertEqualSets( array( $c1, $c2, $c3, $c4, $c5 ), $found ); } + public function test_query_post_id_0() { + $c1 = $this->factory->comment->create( array( 'comment_post_ID' => $this->post_id, 'comment_approved' => '1' ) ); + + $q = new WP_Comment_Query(); + $found = $q->query( array( + 'post_id' => 0, + 'fields' => 'ids', + ) ); + + $this->assertEqualSets( array( $c1 ), $found ); + } + /** * @ticket 12668 */