Problem:
I have 2 custom fields called 'Rating' and 'Count' in a custom field group assigned to a Custom post type.
I want to update the 'Rating' and 'Count' fields whenever a user submits a new rating.
The desired formula for updating the 'Rating' field is 'Rating = (Rating * Count + New Rating Value Given By User)/(Count+1)',
and for the 'Count' field, 'Count = Count + 1'.
Solution:
Add the following code to your functions.php or custom plugin file:
[php]
// Attach the 'update_rating_and_count' function to the 'cred_before_save_data' hook
add_action('cred_before_save_data', 'update_rating_and_count', 10, 2);
// Define the 'update_rating_and_count' function
function update_rating_and_count($form_data) {
// Check if the form submitted has the correct ID (Replace 600 with your Toolset form ID)
if ($form_data['id'] == 600) {
// Check if the '_cred_cred_prefix_post_id' field exists in the form data
if (isset($_POST['_cred_cred_prefix_post_id'])) {
// Get the post ID from the form data
$post_id = $_POST['_cred_cred_prefix_post_id'];
// Get the current rating and count values from the post meta
$rating = (float) get_post_meta($post_id, 'wpcf-rating', true);
$count = (int) get_post_meta($post_id, 'wpcf-count', true);
// Get the new rating value submitted by the user
$new_rating = (float) $_POST['wpcf-rating'];
// Calculate the new average rating value using the provided formula
$new_rating_value = ($rating * $count + $new_rating) / ($count + 1);
// Update the submitted rating value with the new average rating value
$_POST['wpcf-rating'] = $new_rating_value;
// Increment the count by 1
$new_count = $count + 1;
// Update the count value in the post meta
update_post_meta($post_id, 'wpcf-count', $new_count);
}
}
}
[/php]
Replace 600 with your Toolset form ID, and ensure the field names in the code match your setup.
This code attaches the 'update_rating_and_count' function to the 'cred_before_save_data' hook.
When a form with the specified ID (in this case, 600) is submitted, the function retrieves the current rating and count values for the post being edited.
It then calculates the new average rating value based on the user's submitted rating and updates the rating and count values in the post meta.
Relevant Documentation:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_before_save_data