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

Get average product attribute value rating outside loop (WooCommerce)

下面的代码输出循环内所有产品的平均评分(通过简码),如下所示: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' 和值 'twins')

更新:下面的代码完成了工作:)

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');

试试这个:(现在无法测试,可能有语法错误,可能会有所改进。请随时编辑我的答案!)

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();
}

希望我理解正确。