获取平均产品属性值的评价外循环(WooCommerce)

问题描述 投票:1回答:1

下面的代码输出的平均评分(通过短码)的所有产品的循环这样内:3.0 4.0 4.0 5.0

function iw_get_product_ratings_by_attribute_shortcode() {

    // The Query
    $query = new WP_Query( array(
        'posts_per_page' => -1,
        'tax_query' => array(
            'relation'=>'AND',
            array(
                'taxonomy' => 'pa_merk',
                'field' => 'slug',
                'terms' => 'twins'
            )
        )
    ) );

        // The Loop
    if ( $query->have_posts() ) {

        while ( $query->have_posts() ) {
            $query->the_post();

            $rating = get_post_meta( get_the_id(), '_wc_average_rating', true );

            if ($rating != 0) { echo number_format((float)$rating, 1, '.', ''); }

        }

        /* Restore original Post Data */
        wp_reset_postdata();
    }

}

add_shortcode('iw_get_product_ratings_by_attribute', 'iw_get_product_ratings_by_attribute_shortcode');

我怎样才能得到这些数字的整体平均?

换句话说:我想显示的平均评分所有产品(与属性“pa_merk”和值“双胞胎”)

更新:下面的代码做这项工作:)

function iw_get_product_ratings_by_attribute_shortcode() {

    // The Query
    $query = new WP_Query( array(
        'posts_per_page' => -1,
        'tax_query' => array(
            'relation'=>'AND',
            array(
                'taxonomy' => 'pa_merk',
                'field' => 'slug',
                'terms' => 'twins'
            )
        )
    ) );

    // The Loop
    if ( $query->have_posts() ) {

        $ratingSum = 0;
        $postsCount = 0;

        while ( $query->have_posts() ) {
            $query->the_post();

            $rating = get_post_meta( get_the_id(), '_wc_average_rating', true );

            if ($rating != 0) {
                $postsCount++;
                $ratingSum += $rating;
            }

        }

        if ($ratingSum > 0 && $postsCount > 0) {
           return $ratingSum / $postsCount; // todo do the rounding stuff 
        }

        /* Restore original Post Data */
        wp_reset_postdata();
    }
}

add_shortcode('iw_get_product_ratings_by_attribute', 'iw_get_product_ratings_by_attribute_shortcode');
wordpress woocommerce while-loop rating
1个回答
0
投票

试试这个:(现在不能测试它,可能有语法错误,大概可以提高随意编辑我的答案!)

if ( $query->have_posts() ) {

    $ratingSum = 0;
    $postsCount = 0;

    while ( $query->have_posts() ) {
        $query->the_post();
        $postsCount++;

        $rating = get_post_meta( get_the_id(), '_wc_average_rating', true );

        $ratingSum += $rating;

        if ($rating != 0) { echo number_format((float)$rating, 1, '.', ''); }

    }

    if ($ratingSum > 0 && $postsCount > 0) {
       echo $ratingSum / $postsCount; // todo do the rounding stuff 
    }

    /* Restore original Post Data */
    wp_reset_postdata();
}

希望我理解正确你。

© www.soinside.com 2019 - 2024. All rights reserved.