Получить среднюю оценку значения атрибута продукта вне цикла (WooCommerce) - PullRequest
0 голосов
/ 08 февраля 2019

Ниже кода выводит средние оценки (через шорткод) всех продуктов в цикле, как это: 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 голосов
/ 08 февраля 2019

Попробуйте: (не могу проверить это сейчас, могут быть синтаксические ошибки, и, возможно, могут быть улучшены. Не стесняйтесь редактировать мой ответ!)

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

Надеюсь, я вас правильно понял.

...