How to get the average of the values from the comment meta

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!

5 Answers
5

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

add_action("comment_post", "wpse16733_updateAVGs");

function wpse16733_updateAVGs($comment_ID, $approved){

    if ($approved){
        $commentdata=get_comment($comment_ID, ARRAY_A); 
        $parent_post=get_post($commentdata['comment_post_ID']);

        (... get your rating, get post meta, calc and save ...)

    }
}

Leave a Comment