Falch0n Falch0n - 5 months ago 30
PHP Question

Sum and average value from CPT in ACF

I'm trying to echo the average of all ratings from a custom post type, but not getting there.

edit: total value isn't showing up, so I can't calculate the average

I was hoping someone could help me.

$args = array( 'post_type' => 'ratings' );
$ratings = new WP_Query( $args );

$count = $ratings->post_count;
$total = 0;
$average = $total / $count;

while ( have_rows('ratings') ) : the_row();
$total += intval( the_field('rating_num'));
endwhile;

echo $average;
wp_reset_query();

Answer

Try this code,$average = $total / $count; put after the while loop because before the loop $average is 0 and 0/any number = 0

You can used the get_field() for get the "rating_num"

$args = array( 'post_type' => 'ratings' );
$ratings = new WP_Query( $args );

$count = $ratings->post_count;
$total = 0;
//$average = $total / $count;

while ( have_rows('ratings') ) : the_row(); 
    $total += intval( get_field('rating_num'));
endwhile;

$average = $total / $count;
echo $average;
wp_reset_query();

EDIT

Used round()

echo round(3.453546);

//OUTPUT 3

Other option is

number_format(3.453546, 0, '.', '');

//OUTPUT 3
Comments