这是我的版本,基于以上两个答案。它继续运行wp_set_comment_status
更改为approve
.
calc_avg_rating()
统计字段为的注释rating
(如果partuclar注释没有rating
, 它只需继续),当新评论获得批准时,它会更新avg_rating
.
然后,对于我的模板,我只需调用get_product_rating
, 它查看的是avg_rating
, 这样,我们就不会在每次加载页面时都计算所有这些内容。
add_action("wp_set_comment_status", "calc_average_rating");
function calc_average_rating($comment_ID, $approved) {
if ($approved = \'approve\'){
$commentdata=get_comment($comment_ID, ARRAY_A);
$parent_post=get_post($commentdata[\'comment_post_ID\']);
global $wpdb;
$post_id = $parent_post->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
$rating = (round(($average_rating/$counter)*2,0)/2);
} else {
//no ratings
$rating = \'\';
}
update_post_meta($post_id, \'avg_rating\', $rating);
}
}
function get_product_rating() {
$post_id = get_the_ID();
$value = get_post_meta($post_id, \'avg_rating\', true);
return $value;
}
希望这对别人有帮助!