0

I need to be able to sum up all values of a specific custom field and then get the total count.

For example, I have created a custom post type for reviews and each one has custom fields for 5 star rating.

What I need is to add up all the values of the star rating and divide by total count to give me the average.

1

Thanks for your help guys. They didn't quit work exactly, but I managed to get the result I needed by doing the following

$reviewsNum = 0;
$reviewsCount = 0;  
$argsSchema = array( 'post_type' => 'reviews', 'posts_per_page' => -1 );
$loopSchema = new WP_Query( $argsSchema );
$count_reviews = wp_count_posts( 'reviews' )->publish;
while ( $loopSchema->have_posts() ) : $loopSchema->the_post();
    $reviewrating       =   get_post_meta(get_the_ID(), "_reviewrating", true);
    if (!empty($reviewrating)){
        $reviewsNum += $reviewrating;
    }
endwhile;
$averagerating = $reviewsNum / $count_reviews;
0

I did something similar where I added a custom field for the weight of a product. Here's my code:

function epcpt_total_tonnage(){


    $query_args = array(
            'post_type' => 'projects',
            'post_status' => 'publish',
            'order' => 'DESC'
        );


        $total_tonnage = 0;
        $query = new WP_Query($query_args);
        if ( $query->have_posts() ) {
            while( $query->have_posts() ) {
            $query->the_post();
            // do the processing for each post

            $total_tonnage = $total_tonnage + get_field( "tonnage", $post->ID, 123 );
            // $total_tonnage = $total_tonnage + get_post_meta( $post->ID, 'tonnage', true );
            }
        }
        echo '<p>Total output tonnage to date: ' . number_format_i18n( $total_tonnage ) . ' Tonnes</p>';
    }

You can change your post_type to 'reviews' and then amend your get_field() values to suit.

0

Something along the lines of the following should work. I used the get_field function because I noticed you tagged this post with "advanced-custom-fields".

function get_average_rating( $post_id ) {
    $rating_sum = 0;

    $reviews_of_post = get_posts( array(
        'post_type' => 'NAME_OF_YOUR_REVIEW_POST_TYPE',
        'posts_per_page' => -1,
        'meta_query' => array(
            array(
                'key' => 'NAME_OF_A_CUSTOM_FIELD_ON_THE_POST_TYPE_CONTAINING_RELATIONSHIP_TO_POST',
                'value' => $post_id,
                'compare' => '=',
            ),
        ),
    ) );

    if ( empty( $reviews_of_post ) ) {
        return 0; // If there are no reviews, we return 0.
    }

    foreach ( $reviews_of_post as $review ) {
        $rating_sum += get_field( 'NAME_OF_CUSTOM_FIELD_CONTAINING_RATING', 'post_' . $review->ID);
    }

    return $rating_sum / count( $reviews_of_post );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.