您在中有输入错误$post->ID
由于您没有$post变量,而且它确实可能会让您觉得它不起作用,至少它不会计算新的值。这是一种改进的方法。
我还使用了不同的钩子来触发真正必要的操作,而不是针对每个comment\\u状态转换。
/**
* Gets comment average data.
*
* @param int $post_id
*/
function sw_update_average_review_rating( $post_id ) {
if ( get_post_type( $post_id ) === \'review\' ) {
$prev_averating = get_post_meta( $post_id, \'wp_review_comments_rating_value\', true );
$prev_count = get_post_meta( $post_id, \'wp_review_comments_rating_count\', true );
$comments = get_comments(
array(
\'post_id\' => $post_id, // HERE was a typo error, you dont\' have here a $post you have $post_id!
\'type\' => \'wp_review_comment\',
\'status\' => \'approve\',
)
);
$ratings_sum = 0;
foreach ( $comments as $comment ) {
$ratings_sum += get_comment_meta( $comment->comment_ID, \'wp_review_comment_rating\', true );
};
$count = count( $comments );
$ave_reviews = $ratings_sum / $count;
$averating = round( $ave_reviews, 2 );
update_post_meta( $post_id, \'wp_review_comments_rating_value\', $averating, $prev_averating );
update_post_meta( $post_id, \'wp_review_comments_rating_count\', $count, $prev_count );
}
}
/**
* Hook action for to trigger recalculation after comment status got changed.
*
* @param $comment_id
* @param WP_Comment $comment
*/
function sw_review_after_comment_status_changed( $comment_id, $comment ) {
$post_id = $comment->comment_post_ID;
$post = get_post( $post_id );
if ( \'review\' === $post->post_type ) {
// trigger calculation.
sw_update_average_review_rating( $post_id );
}
}
add_action(\'deleted_comment\', \'sw_review_after_comment_status_changed\', 10, 2);
add_action( \'trashed_comment\', \'sw_review_after_comment_status_changed\', 10, 2);
// hooks below can be tuned only to handle your custom comment type.
add_action( \'comment_approved_\', \'sw_review_after_comment_status_changed\', 10, 2);
add_action( \'comment_unapproved_\', \'sw_review_after_comment_status_changed\', 10, 2);
// Tuned for your custom comment type to trigger only for them, use either these or pair of hooks above.
add_action( \'comment_approved_wp_review_comment\', \'sw_review_after_comment_status_changed\', 10, 2);
add_action( \'comment_unapproved_wp_review_comment\', \'sw_review_after_comment_status_changed\', 10, 2);