【问题标题】:WooCommerce: Get average rating from multiple products [duplicate]WooCommerce:从多个产品中获得平均评分 [重复]
【发布时间】:2022-01-28 16:17:21
【问题描述】:

我有一个自定义循环,用于根据产品 ID 列表获取产品列表。 现在我尝试获取该循环内所有产品的总评分和平均评分。

评分总数不是问题。 我的问题是我没有从 cmets 获得星级。 (我正在使用插件“WooCommerce Product Reviews Pro”)

这是我目前的循环:

<?php $args = array (
    'post_type' => 'product',
    'number'  => '-1',
    'post__in' => $product_ids,
    'meta_key' => 'rating',
    'orderby' => 'meta_value_num',
    'order' => 'DESC'
);
$comments = get_comments( $args );

echo count($comments);
?>
<?php if ( !empty($comments) ) : ?>
    <pre><?php print_r($comments); ?></pre>

    <?php foreach ( $comments as $comment ) {

        echo $comment_ID = $comment->comment_ID;

    } ?>

<?php endif; ?>

有了echo count($comments),我得到了总评分。

但如果我选择print_r($comments),我看不到评论的星级。

我想我需要为此使用评论 ID。

使用foreach,我将所有评论 ID 作为字符串。

但我不确定在哪里查看以及如何添加所有评分来为循环中的选定帖子生成新的平均评分。

编辑:我找到了另一种达到平均收视率的方法。 这次我循环浏览帖子而不是 cmets。

所以我可以得到每个产品的平均评分。

问题在于,如果没有 cmets/reviews,那么在该循环中还有带有 0 的评级。

到目前为止,这是产品的循环:

$average_ratings = array();

foreach ( $posts as $post ) {

    global $product;
    echo $average_ratings[] = $product->get_average_rating();

}

var_dump($average_ratings);

【问题讨论】:

    标签: php wordpress woocommerce comments review


    【解决方案1】:

    我找到了答案。这是我的代码:

    <?php
    $args = array (
        'post_type' => 'product',
        'post__in' => $product_ids,
        'meta_key' => 'rating',
        'orderby' => 'meta_value_num',
        'order' => 'DESC'
    );
    $comments = get_comments( $args );
    
    $total_ratings = count($comments);
    ?>
    <?php if ( !empty($comments) ) : ?>
    
        <?php
        $average_ratings = array();
        foreach ( $comments as $comment ) {
            $comment_post_ID = $comment->comment_post_ID;
            $product = wc_get_product( $comment_post_ID );
            $average_ratings[] = $product->get_average_rating();
        }
    
        $average_ratings = array_filter($average_ratings);
        $average = array_sum($average_ratings)/count($average_ratings);
        echo $average;
        ?>
    
    <?php endif; ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      相关资源
      最近更新 更多