【问题标题】:WordPress count custom post type Advanced Custom FieldWordPress 计数自定义帖子类型高级自定义字段
【发布时间】:2018-01-29 15:21:53
【问题描述】:

我有 WordPress 网站和插件 Advanced Custom Fields,我为推荐创建了一个自定义帖子,里面是一个名为“ratings”的自定义字段,您可以在其中输入一个数字,例如1、3.5、5等

我想从每个帖子的字段中取出所有数字,然后将它们加起来为 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;
?>  

【问题讨论】:

    标签: php wordpress advanced-custom-fields


    【解决方案1】:

    尝试使用此代码。改了posts_per_page =&gt; -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.
    

    希望,这对你有帮助。谢谢。

    【讨论】:

    • 感谢您的回复,它返回为“2”,这不太正确。我想把所有的评分加起来,所以 5 + 4 = 9 加在一起?
    【解决方案2】:

    他几乎做对了。只需将 count() 替换为 array_sum()

    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
    

    【讨论】:

    • 如果我也想要统计数据的平均值,那么在 30 条评论中他们得到 4.97 分(满分 5 分)?我将如何调整它以实现这一目标?谢谢
    • 修改了我的答案以计算平均值。
    • 谢谢,我又添加了 2 个推荐来测试,其中一个给了它 4 颗星,平均值为; 4.8571428571429 此外,尽管现在有 7 条评论,但它仍然显示 5 条评论?...
    猜你喜欢
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多