Hi Luoy,
Thanks for your response.
I'll do my best to explain what I want to accomplish. This is also related to post #259660
(https://toolset.com/forums/topic/where-are-custom-fields-stored-in-the-database-wordpress-custom-query/)
Essentially, I'm trying to create a rating system for using 'custom post types' + 'custom fields' for movies, where 'ratings' are children of 'movies.' The problem with other solutions that I've tried until now via 'Toolset' is that average ratings were calculated 'on-the-fly' and not stored in the DB, hence filtering by ratings was impossible.
Simply, I want to store the 'Average Rating' in the database as a WPCF upon CRED submission, using the CRED submission itself to calculate the most the average. 'wpcf-rating' is a field in the child post, 'Rating' and 'wpcf-rating-average' is a field in the parent post 'Movie.'
To try to break it down, I want to:
1) Pull the value from a CRED form 'wpcf-rating', let's call this 'U' {I need this part}
2) Sum all of the values of 'wpcf-rating' where these are child posts of a set ID (33), let's call this 'S' {I need this part}
3) Add the value from 'wpcf-rating' the CRED form to the SUM of all 'wpcf-rating' values that are child posts of a set ID (33) {I need this part}
4) Count all child posts, where the parent ID is set (33), let's call this 'C' and add '1' to it to take into account the current CRED submission
5) Calculate the average {simple}
6) Store this average in the database {I have this part}
So, the average to store would be
(U + S) / (C + 1) = R
'R' = wpcf-rating-average
This is the code that I have for now:
add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($post_id, $form_data) {
if ($form_data['id']==48) {
$parent_id = $_GET['parent_movie_id'];
$current_reivew = $_POST['wpcf-rating']; // Not working, need to get $wpcf-rating from current cred form submission
$post_type = "'reviews'";
global $wpdb;
$review_count = 1 + $wpdb->get_var( "SELECT COUNT(ID) FROM $wpdb->posts WHERE post_type = $post_type " );
$review_sum = ''; // need sum of all 'wpcf-rating' values where parent post is $parent_id
$average_rating = $review_sum / $review_count;
update_post_meta($parent_id, 'wpcf-average-rating', $average_rating);
}
};
I really hope this makes sense and I'm happy to answer any questions that you might have.
Best,
Ryan