I used the comment meta to add a simple rating system. The user can post a rate from the comment form from where I added 3 dropdown comment meta.
The rating is working well, reflecting the ratings together with the comment written by the user. My only problem now is this: how can I get the average of all the ratings posted? I need the average to be placed on the post content.
My rating system rates the following:
- Price,
- Packaging,
- Quality.
I want an average for each rate:
- Average Price Rate,
- Average Packaging Rate, and
- Average Quality Rate.
Thank you so much!
If you need to show the averages in the content, you need to pre-calculate them (before showing the comments).
My approach would be having a custom meta in the post with the calculated averages and modify those metas every time a new comment (rating) is saved.
Something like
I’ve got something similar using a custom query to calculate the average on the fly – per Rabino’s comment, it would be more efficient to store the result of this function as a meta value, but I’d want it triggered when a comment is approved, rather than when a comment is saved.
here’s your function:
In my context I have a 1-5 rating. no results of the query means no ratings provided.
Drop the following in the loop and you’re good to go:
Similar to PaulIsLoud’s answer, but calculates the average directly in the query instead of iterating the results
Here’s my version, based on both of the answers above. It runs on
wp_set_comment_status
changed toapprove
.calc_avg_rating()
counts comments having a field ofrating
(if a partuclar comment has norating
, it simply moves on), and when a new comment is approved, it updates the post meta value ofavg_rating
.Then, for my template, I simply call
get_product_rating
, which looks at the post meta field ofavg_rating
, that way we’re not calculating all of this every time the page is loaded.Hope this helps someone!
This is a solution which will display the average after the last comment. As a workaround you could simply do two
have_comments()
comments loops and calculate the average rating with the first loop and display the comments with the second loop.