Exclude comments from a WP_Query object?

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?

1 Answer
1

Did you actually find a case where there are any real comments in the wp-query object after running a normal query?

If you examine the code in class-wp-query.php, you should find that the comments field only is populated with comments when a “comments-feed” is being queried for.

In normal operation, comments are not retrieved by the WP_Query, but instead retrieved by using WP_Comment_Query, and this does not happen until your theme calls the comments_template() function.

As such, you can use the ‘comments_template_query_args’ filter to filter the arguments passed to that class before the comments are displayed on the page. This won’t affect the comments feed, because those are indeed populated by the main WP_Query, but only for the comments feed case.

Leave a Comment