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:
function average_rating() {
global $wpdb;
$post_id = get_the_ID();
$ratings = $wpdb->get_results("
SELECT $wpdb->commentmeta.meta_value
FROM $wpdb->commentmeta
INNER JOIN $wpdb->comments on $wpdb->comments.comment_id=$wpdb->commentmeta.comment_id
WHERE $wpdb->commentmeta.meta_key='rating'
AND $wpdb->comments.comment_post_id=$post_id
AND $wpdb->comments.comment_approved =1
");
$counter = 0;
$average_rating = 0;
if ($ratings) {
foreach ($ratings as $rating) {
$average_rating = $average_rating + $rating->meta_value;
$counter++;
}
//round the average to the nearast 1/2 point
return (round(($average_rating/$counter)*2,0)/2);
} else {
//no ratings
return 'no rating';
}
}
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:
<?php echo average_rating(); ?>