2016-06-09 96 views
0

我試圖迴應自定義帖子類型中所有評分的平均值,但沒有達到此值。ACF中CPT的總和和平均值

編輯:總價值沒有顯示出來,所以我不能計算平均

我希望有人能幫助我。

$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(); 
+0

嗨解決了!請詳細說明什麼是不工作/你得到什麼錯誤? – Epodax

+0

嗨!總價值沒有顯示出來,所以我無法獲得平均值 – Falch0n

+0

「評級」行中的字段'rating_nums'是否存在並且有可轉換爲整數的值? – Dilettant

回答

1

因爲迴路$average00/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(); 

之前試試下面的代碼中,while循環之後$average = $total/$count;放編輯

使用round()

echo round(3.453546); 

//OUTPUT 3 

其他選項是

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

//OUTPUT 3 
+0

這段代碼不適合我,也許是因爲行不存在。 – Falch0n

+0

@ Falch0n檢查我的更新回答 –

+0

@ Falch0n檢查編輯答案 –

0

我沒有得到正確評價的價值。現在我有這個,問題主要解決。

唯一的最後一個問題是,該值以循環小數結尾。我怎麼能通過整數來整理價值?例如'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);