Hello Toolset team,
I want to create a rating system and for testing the functionality I created the same CPT (“company” and “company-review”) and same fields as mentioned in this post:
https://toolset.com/forums/topic/save-child-post-field-average-and-count-to-parent-post-field/
Then I added the following code to my function.php
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'];
$reviews = toolset_get_related_posts($parent_post,'company-company-review','parent',999,0,array(),'post_object','child');
$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_submit_complete', 'update_company_review', 10, 2);
After I have done this I added a new rating with link “Create new” but the fields in the parent post Company 1 have not changed. Could it be that I miss another code? I have gone through the related post mentioned in the above link and also trough the links and sublinks there. Now I am not sure what additional code is needed, is it a Form's hook or shortcode …
It would be great if you can support me on this case and I think this is also beneficial for many other users of Toolset.
Thanks in advance and best whishes
Andreas