How to query comments only for the current post?

I am using ACF and my comments have custom fields. I also have custom post type called cars.

What I'm trying to do is to make users comment their average consumption, and then I calculate average consumption for single car.

I did that, and it works well except one part. Average consumption is same for all cars, even each car has different average consumption.

For example:

  • Car 1 mpg (28;25;39 - avg 30.6)
  • Car 2 mpg (44;50 avg 47)

And when user goes to Car 1, avg should be 30.6 and Car 2 should show 47. Instead each car has same value and it's avg mpg on from all fields (28;25;39;44;50 avg 37.2)

Here is my code. I have followed ACF documentation on getting values from comments

 ?php
$args             = array();
$comments_query   = new WP_Comment_Query;
$comments_count   = wp_count_comments();
$comments         = $comments_query-query($args);
if ($comments) {
    foreach ($comments as $comment) {
        $total += get_field('mpg', $comment);
    }
} else {
    echo 'No comments found.';
}
$average = $total / $comments_count-total_comments;
echo round($average, 2);
wp_reset_query();
?

This code is in single-cars.php (custom post type) and it does the calculation but from all comments for all posts, and I want to show calculation for single car.

Thanks in advance

Topic wp-comment-query advanced-custom-fields comments Wordpress

Category Web


Your arguments for the comment query is empty, so it returns every comment on the planet. You should specify the post ID, to get comments that belong to that post.

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

Take a look into the codex page for more information about arguments.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.