I have a custom post type of "company" with a child custom post type of "company-review".
The "company" post type has 2 fields of "company-ratings-average" and "company-ratings-total"
The "company-review" custom post type has a custom field of "company-rating".
There is a cred form with ID 722. That cred form is on the company post type page and when a user fills out that cred form it creates a "company-review" child post attached to the company post. The cred form has the field of "company-rating".
What I want is when a user fills out that cred form it populates the "company-ratings-average" field of the "company" with the average of all the "company-rating" fields and the "company-ratings-total" with the total number of company-review child posts.
I am following along with this post: https://toolset.com/forums/topic/sort-by-highest-rated/
Here is my code:
function update_company_review($post_id, $form_data) {
// if specific form, change ID to the CRED "Review" ID
if ($form_data['id'] == 722) {
// Get ID of Company Being Reviewed
$parent_post = $_POST['@company-company-review_parent'];
$args = array(
'posts_per_page' => -1,
'post_type' => 'company-review',
'meta_key' => '@company-company-review_parent',
'meta_value' => $parent_post,
);
$reviews = get_posts($args);
$sum = 0;
$num = 0;
foreach ($reviews as $review) {
$ratings = get_post_meta($review->ID, 'wpcf-company-rating', true);
if ($ratings) {
$sum += $ratings;
$num++;
}
}
$average = ($num > 0) ? $sum / $num : 0;
// You can keep or adjust the rounding logic as needed
$res = round($average * 2) / 2; // Rounds to nearest 0.5
update_post_meta($parent_post, 'wpcf-company-ratings-average', $res);
update_post_meta($parent_post, 'wpcf-company-ratings-total', $num);
}
}
add_action('cred_save_data', 'update_company_review', 10, 2);
My issue is that the "company-ratings-average" and "company-ratings-total" fields just end up being 0.
Any help is appreciated and let me know if you need more info.