2

我想在首页显示客户评论的总数,我试过这个方法:

<?php
  $args = array(
    'status'   => 'approve',
    'post_status' => 'publish',
    'post_type'   => 'product'
  );
  $comments_query = new WP_Comment_Query;
  $comments = $comments_query->query( $args );
  $count = get_comment_count($comments);
?>

<span class="total_reviews">
  <?php echo $count['approved'] . ' reviews' ?>
</span>

但是没有像我想要的那样工作!例如,我有 4 条评论,此代码仅显示(1 条评论)而不是(4 条评论)。

平均而言,我不知道它在主页上是如何工作的,我只知道如何使用下面的代码在单个产品页面上实现它:

$average = $product->get_average_rating();

但是,此代码仅适用于单个产品的平均评分,而不是我想要的所有评论的全球平均值。

任何帮助表示赞赏。

4

1 回答 1

3

更新 (避免在还没有评论时上一个函数出错)

您将在下面找到 4 个自定义函数,它们将为您提供:

  1. 产品评论总数
  2. 产品评级计数数据,将用于:
    • 产品按评级输出 html 计数
    • 产品评分平均输出 html

功能代码:

function get_total_reviews_count(){
    return get_comments(array(
        'status'   => 'approve',
        'post_status' => 'publish',
        'post_type'   => 'product',
        'count' => true
    ));
}

function get_products_ratings(){
    global $wpdb;

    return $wpdb->get_results("
        SELECT t.slug, tt.count
        FROM {$wpdb->prefix}terms as t
        JOIN {$wpdb->prefix}term_taxonomy as tt ON tt.term_id = t.term_id
        WHERE t.slug LIKE 'rated-%' AND tt.taxonomy LIKE 'product_visibility'
        ORDER BY t.slug
    ");
}

function products_count_by_rating_html(){
    $star = 1;
    $html = '';
    foreach( get_products_ratings() as $values ){
        $star_text = '<strong>'.$star.' '._n('Star', 'Stars', $star, 'woocommerce').'<strong>: ';
        $html .= '<li class="'.$values->slug.'">'.$star_text.$values->count.'</li>';
        $star++;
    }
    return '<ul class="products-rating">'.$html.'</ul>';
}

function products_rating_average_html(){
    $stars = 1;
    $average = 0;
    $total_count = 0;
    if( sizeof(get_products_ratings()) > 0 ) :
        foreach( get_products_ratings() as $values ){
            $average += $stars * $values->count;
            $total_count += $values->count;
            $stars++;
        }
        return '<p class="rating-average">'.round($average / $total_count, 1).' / 5 '. __('Stars average').'</p>';
    else :
        return '<p class="rating-average">'. __('No reviews yet', 'woocommerce').'</p>';
    endif;
}

代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。

用法

  1. 总客户评论:

    echo '<p>'.__('Total reviews','woocommerce').': '.get_total_reviews_count().'</p>';
    
  2. 产品按评级列表计数:

    echo products_count_by_rating_html();
    
  3. 产品评分平均:

    echo products_rating_average_html();
    
于 2018-05-30T23:48:53.800 回答