I have noticed that the default WP_Query object also contains all of a post’s comments.

global $wp_query;

print_r($wp_query->comments);
// Prints an object containing all of a post's comments

From my understanding, WordPress somehow combines a post query and a comments query into one WP_Query object, and then displays a post’s comments by reading the $wp_query->comments object.

However, I need to query comments and order them by passing advanced query args. So I use WP_Comment_Query to create a new object that contains all of a post’s comments in the order I need them.

$args = array(      
    'post_id' => get_the_ID(),
    'order' => 'ASC'
);

$comments_query = new WP_Comment_Query;
$comments = $comments_query->query($args);

print_r($comments);
// Prints an object containing all comments matching the query

But now it seems that using WP_Comment_Query basically makes WordPress load all of a post’s comments twice.

Obviously, from a performance perspective, this is undesirable, seeing as I don’t actually use the default WP_Query‘s comment object to display my comments.

So I’m wondering: Is it possible to prevent the WP_Query from grabbing a post’s comments, so that I can later grab them ‘manually’ using WP_Comment_Query? And so, preventing the same comments from being grabbed from the database twice?

Read more here: Exclude comments from a WP_Query object?


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: