0
votes

I have WordPress site and the plugin Advanced Custom Fields, I have created a custom post for testimonials, inside is custom field called 'ratings' where you in put a number e.g. 1, 3.5, 5 etc.

I want to take all the number from the field for each post and add them up to a total or average out of 5.

However I'm struggling I can get it to populate the ratings e.g. 5, 5

But I can't get them to add up, can any one help please?

This is what I have below so far...

<?php 
    $args = array( 'post_type' => 'testimonial', 'posts_per_page' => 9999 );
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
?>
    <?php 
        $count = (get_field('rating'));
        print_r($count);
        $add = count($count);
        return $add;
        echo $add;
    ?>    
<?php
    endwhile;
?>  
2

2 Answers

0
votes

He almost got it right. Just replace count() with array_sum()

global $post;
$count = array(); // define $count as array variable
$args = array( 'post_type' => 'testimonial' 'posts_per_page' => -1, 'offset'=> 1);
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); 
   // push rating value inside the $count array
   $count[] = get_post_meta($post->ID, 'rating', true); 
endforeach; 
wp_reset_postdata();

$add = array_sum($count);  // You can use this variable outside also.
echo $add;  // print total rating.
echo $add/count($count) // Print average
0
votes

Try using this code. changed posts_per_page => -1

global $post;
$count = array(); // define $count as array variable
$args = array( 'post_type' => 'testimonial' 'posts_per_page' => -1, 'offset'=> 1);
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); 
   // push rating value inside the $count array
   $count[] = get_post_meta($post->ID, 'rating', true); 
endforeach; 
wp_reset_postdata();

$add = count($count);  // You can use this variable outside also.
echo $add;  // print total rating.

Hope, This will helpful for you. Thanks.