I would like to save some PHP memory when quering category page (like 5000 products at once) with average review rating, so I would like to save average rating of reviews every time I will manually approve new comment.
I would like to accomplish, whenever I click on "APPROVE" button in administration, it will run these php scripts.
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
and trim(coalesce($wpdb->commentmeta.meta_value, '')) <>''
");
$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 '0';
}
}
$ar = average_rating();
add_post_meta( $post->ID, 'summary', $ar );