外部获取平均产品属性值评级(WooCommerce)

时间:2019-02-08 13:58:03

标签: wordpress woocommerce while-loop rating

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

1 个答案:

答案 0 :(得分: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();
}

希望我能正确理解你。