Tell us what you are trying to do?
I'm trying to write a function for calculating the value of a field when the post is updated based on the value of a different field in all related posts of a different type. Here is what I have so far with notes on what I'm trying to accomplish in each line.
// When a Staff Member bio is created or updated, trigger the updateStaffReviewStats() function.
add_action('save_post_{$post->staff}', 'updateStaffReviewStats', 10, 1);
// Function for updating the aggregate review rating and review count for a staff member
function updateStaffReviewStats($post_ID) {
// Find out if there are any reviews related to the Staff Member
$myReviews = toolset_get_related_posts(
$post_ID,
'staff-member-review',
[
'query_by_role' => 'parent',
'role_to_return' => 'other',
'args' => [ 'post_status' => 'published' ]
]
);
// If there are no related reviews, exit function
if(!$myReviews) { return; }
// Otherwise set reviewSum and reviewCount to 0
$reviewSum = 0;
$reviewCount = 0;
// Loop through related reviews
foreach($myReviews as $review) {
// Calculate the average rating value
$reviewSum = $reviewSum + $review['wpcf-review-rating'];
// Count total number of reviews
$reviewCount++;
}
// Calculate the average and store it in $avgRating
$avgRating = $reviewSum / $reviewCount;
// store avgRating in the wpcf-aggregate-staff-member-rating field for the current staff member
// store the count in the wpcf-total-reviews-for-staff-member field for the current staff member
// Update post 37
$staff_post = array(
'ID' => $post_ID,
'wpcf-aggregate-staff-member-rating' => $avgRating,
'wpcf-total-reviews-for-staff-member' => $reviewCount
);
// Update the post into the database
wp_update_post( $staff_post );
}
When I update a test post of type "staff" that has multiple reviews associated with it, nothing seems to happen, and I'm not 100% sure where to go from here with regard to troubleshooting.
Any guidance you can give with regard to using the toolset api would be greatly appreciated. I know this is beyond the scope of your normal support, so if you can't help me I completely understand. Even a nudge in the right direction would be appreciated.
You seem to be treating custom fields (stored in wp_postmeta) as if they were standard fields that are part of the post object (those stored in wp_posts).
Thank you Nigel... this is all VERY helpful. I appreciate the gentle nudge in the right direction. I haven't been able to jump back into this quite yet but I wanted to thank you for your time before my ticket was auto-closed. 🙂