I have set up 2 CPT: Object and Reviews
Reviews have several numeric custom fields that represent ratings on several criteria (style, size...)
I have properly set up a "one to many" relationship with the most recent beta: object-review
ONE object can have MANY reviews. But one review can only be attached to a single object.
I have set up a CRED form with the new relationship field so I can create a review and attach it to an existing object.
Also I have a content template for objects that properly shows all attached reviews to the current shown object.
What I want to to:
I want to calculate an average for each criterion with a shortcode. So I need to query all related reviews for one object and get an average from the various meta fields for criterion1 from any of those related reviews found.
The following code would be the old style solution (adapted from: https://toolset.com/forums/topic/setting-up-a-ratings-average-for-reviews-cpt/)
//SHORTCODE FOR AVERAGE RATING ON CRITERION 1
add_shortcode('rating-average_criterion1', 'rating_average_func_criterion1');
function rating_average_func_criterion1() {
global $post;
$args = array(
'post_type' => 'reviews',
'meta_key' => '_wpcf_belongs_' . $post->post_type . '_id',
'meta_value' => $post->ID,
);
$child_posts = get_posts($args);
$sum = 0;
$num = 0;
foreach ($child_posts as $child_post) {
$ratings = get_post_meta($child_post->ID, 'wpcf-criterion1', true);
if($ratings)
{
$sum += $ratings;
$num ++;
}
}
$average = 0;
if($num>0)
{
$average = $sum/$num;
}
return $average;
}
I currently have no clue how to further adapt this to use the new Relationships API. Could you please guide me in the right direction?
https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/
Thanks in advance
After some testing I finally found the solution ?
This helped: https://toolset.com/forums/topic/new-post-relatsionships-api-call-to-undefined-function/
//SHORTCODE FOR AVERAGE RATING ON CRITERION1
add_shortcode('avg-criterion1', 'rating_average_func_criterion1');
function rating_average_func_criterion1() {
$child_posts = toolset_get_related_posts(
get_the_ID(), //Post to query by.
'object-review', //Slug of the relationship to query by
'parent', //Name of the element role to query by.
100, //Maximum number of returned results
0, //Result offset
array(
'meta_key' => 'wpcf-criterion1',
'orderby' => 'meta_value',
'order' => 'ASC',
),//Additional query arguments - this might be unneccessary in my case
'post_id', //Determines return type
'child' // which posts from the relationship should be returned
);
$sum = 0;
$num = 0;
foreach ($child_posts as $child_post) {
$ratings = get_post_meta($child_post, 'wpcf-criterion1', true);
if($ratings) {
$sum += $ratings;
$num++;
}
}
$average = 0;
if($num>0) {
//$average = $sum/$num; // dont use this since $num might be wrong if one rating is 0
$average = round($sum/count($child_posts), 1);
}
return $average;
}