1

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

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.