2017-08-21 53 views
0

我有WordPress網站和插件高級自定義字段,我創建了一個自定義帖子的評論,裏面是自定義字段稱爲'收視率',你在哪裏把數字例如1,3.5,5等WordPress計數自定義帖子類型高級自定義字段

我要採取一切人數從現場的每個崗位,並把它們加起來的總或平均出5

但我掙扎,我可以得到它填充收視率,例如5,5

但我不能讓他們加起來,任何人都可以幫忙嗎?

這是我下面到目前爲止...

<?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; 
?> 

回答

0

他幾乎說得對。只需用array_sum()代替count()

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

爆炸,歡呼! – Sam

+0

如果我在統計數據中同樣需要平均數,那麼在30條評論中,他們得到了5分中的4.97分?我將如何調整它來實現這一目標? 謝謝 – Sam

+0

修改我的答案來計算平均值。 –

0

嘗試使用此代碼。改變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. 

希望,這將會對你有幫助。謝謝。

+0

感謝您的回覆,它回到'2',這是不完全正確的。 我想加上所有的收視率,所以5 + 4 = 9一起? – Sam

相關問題