2017-08-21 59 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

相关问题