(WordPress/WPDB/WP Customer Reviews) Counting number of 1*, 2*, 3*, 4*, and 5* reviews?

I successfully added an “average rating” to my site from a snippet I found, but my PHP isn’t great and I’d ideally like to show how many 1*, 2*, 3*, 4*, and 5* reviews each have been made, if that makes any sense.

So I could show it like this on my site:

  • 1* Reviews: 2

  • 2* Reviews: 4

  • 3* Reviews: 3

  • 4* Reviews: 12

  • 5* Reviews: 34

Anyone with decent PHP knowledge will probably be able to figure this out from the code I already used for the average rating, which is below:

<?php global $wpdb;
    $pId = $post->ID; //if using in another page, use the ID of the post/page you want to show ratings for.
    $row = $wpdb->get_results("SELECT COUNT(*) AS `total`,AVG(review_rating) AS `aggregate_rating`,MAX(review_rating) AS `max_rating` FROM wp_wpcreviews WHERE `page_id`= $pId AND `status`=1");
    $max_rating = $row[0]->max_rating;
    $aggregate_rating = $row[0]->aggregate_rating; 
    $total_reviews = $row[0]->total;
    $totl = $aggregate_rating * 20;

<div id="overall-rating">
    <div class="sp_rating" id="wpcr_respond_1">
        <div class="base">
            <div style="width: <?php echo $totl;?>%" class="average"></div>
        <br />
        <p>From <?php echo ' ' . $total_reviews;?> reviews</p>

As you can see the ratings from 1 to 5 are stored in a column called “review_rating” inside the “wp_wpcreviews” table, so is there a way for me to count each rating respectively?

The values in the “review_rating” table are just stored as “1”, “2”, “3”, “4”, or “5”.

Thanks in advance for any responses, been stuck on this for a while!

Source: wpdb

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.