ACF 中 CPT 的总和和平均值
Sum and average value from CPT in ACF
我正在尝试从自定义 post 类型中回显所有评分的平均值,但没有达到目的。
编辑:未显示总价值,因此我无法计算平均值
我希望有人能帮助我。
$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();
试试这个代码,$average = $total / $count;
放在 while
循环之后,因为在循环之前 $average
是 0
和 0/any number = 0
您可以使用 get_field() 获取 "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
已使用 round()
echo round(3.453546);
//OUTPUT 3
其他选项是
number_format(3.453546, 0, '.', '');
//OUTPUT 3
我没有得到正确的评分值。现在有了这个,问题基本解决了
唯一的最后一个问题是该值以无限小数结尾。我如何通过整数将值四舍五入?那么例如“3,453546”变成“3”?
$args = array( 'post_type' => 'ratings' );
$ratings = new WP_Query( $args );
$count = $ratings->post_count;
$total = 0;
if( $ratings->have_posts() ) :
while( $ratings->have_posts() ) : $ratings->the_post();
$total += intval( get_field('rating_num'));
endwhile;
endif;
$average = $total / $count;
echo $average;
wp_reset_query();
编辑:问题已通过使用
解决
round( $average, 1 );
我正在尝试从自定义 post 类型中回显所有评分的平均值,但没有达到目的。
编辑:未显示总价值,因此我无法计算平均值
我希望有人能帮助我。
$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();
试试这个代码,$average = $total / $count;
放在 while
循环之后,因为在循环之前 $average
是 0
和 0/any number = 0
您可以使用 get_field() 获取 "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
已使用 round()
echo round(3.453546);
//OUTPUT 3
其他选项是
number_format(3.453546, 0, '.', '');
//OUTPUT 3
我没有得到正确的评分值。现在有了这个,问题基本解决了
唯一的最后一个问题是该值以无限小数结尾。我如何通过整数将值四舍五入?那么例如“3,453546”变成“3”?
$args = array( 'post_type' => 'ratings' );
$ratings = new WP_Query( $args );
$count = $ratings->post_count;
$total = 0;
if( $ratings->have_posts() ) :
while( $ratings->have_posts() ) : $ratings->the_post();
$total += intval( get_field('rating_num'));
endwhile;
endif;
$average = $total / $count;
echo $average;
wp_reset_query();
编辑:问题已通过使用
解决round( $average, 1 );