以下几点应该可以奏效。我使用了get\\u field函数,因为我注意到您在这篇文章中标记了“高级自定义字段”。
function get_average_rating( $post_id ) {
$rating_sum = 0;
$reviews_of_post = get_posts( array(
\'post_type\' => \'NAME_OF_YOUR_REVIEW_POST_TYPE\',
\'posts_per_page\' => -1,
\'meta_query\' => array(
array(
\'key\' => \'NAME_OF_A_CUSTOM_FIELD_ON_THE_POST_TYPE_CONTAINING_RELATIONSHIP_TO_POST\',
\'value\' => $post_id,
\'compare\' => \'=\',
),
),
) );
if ( empty( $reviews_of_post ) ) {
return 0; // If there are no reviews, we return 0.
}
foreach ( $reviews_of_post as $review ) {
$rating_sum += get_field( \'NAME_OF_CUSTOM_FIELD_CONTAINING_RATING\', \'post_\' . $review->ID);
}
return $rating_sum / count( $reviews_of_post );
}