
Hi,
I’ve created the following function. Basically, the function will do the average of my CPT “ratings” and update the “rating_global” field in my CPT “Product” :
function my_acf_udpate_value ($post_id) {
$rating_sum = 0;
$reviews_of_post = get_posts( array(
'post_type' => 'ratings',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'product',
'value' => $post_id,
'compare' => '=',
),
),
) );
if ( empty( $reviews_of_post ) ) {
return 0;
}
foreach ( $reviews_of_post as $review ) {
$rating_sum += get_field( 'single_rating', 'post_' . $review->ID);
}
return number_format((float)($rating_sum / count( $reviews_of_post )),1, '.', '');
}
add_filter('acf/update_value/name=rating_global', 'my_acf_udpate_value', 10, 3);
Actually, it works but only once. Let’s say I save 3 ratings, then I go to my product and update. The field rating_global is updated with the correct value. If I update on more time, the field rating_global shows 0. I need to re-update my ratings and my product in order to see the correct value…
Any idea ?
Hi,
I’ve managed using save_post :
function my_acf_save_post_6 ($post_id) {
$reviews_of_post = get_posts( array(
'post_type' => 'ratings',
'meta_query' => array(
array(
'key' => 'product',
'value' => '"' . get_the_ID() . '"',
'compare' => 'LIKE',
),
),
) );
foreach ( $reviews_of_post as $review ) {
$rating_sum += get_field( 'single_rating', 'post_' . $review->ID);
}
$value = $rating_sum/count($reviews_of_post);
// do something
update_field('field_5de8d2cf1b919', $value, $post_id);
}
add_action('acf/save_post', 'my_acf_save_post_6', 20);
My only issue now, is that I have to go to my Product post and I still have to update in order to see the rating.
How can I “auto-update” the value without needing to re-publish ?