Oct 22, 2012
kalpesh

WordPress: Show total/aggregate ratings and reviews to your posts/pages

After struggling for finding the way to show aggregate ratings and total number of reviews for the wordpress plugin WP Customer Reviews, I wrote it myself by studying their code. There has been several requests for this feature in their support page and around but they didn’t seem to be interested or didn’t got enough time to wrote this.

Okay, so for all the people who have been struggling to get total and/or aggregate number of ratings and reviews, here is the code that can work on any page/post.

1
2
3
4
5
6
7
8
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;
$wpdb->flush();


To show aggregate ratings in star form, simply add this:

1
<div class="sp_rating" id="wpcr_respond_1"><div class="base"><div style="width: <?php echo $totl;?>%" class="average"></div></div><?php echo ' ' . $total_reviews;?> Reviews</div>

Note: In the above code, please check the formatting of PHP tags, sometimes it’s just not formatted proper and as a result there will be wrong ratings displayed.

For displaying it as,
Overall: 4.67 stars for 60 reviews.

1
echo "Overall: " . $aggregate_rating . " stars for " . $total_reviews . " reviews.";

63 Comments

  • hi, will this work in category.php? i tried inserting the code in category.php, but nothing shows up. thanks

    • have you echo’ed the variables you need to show? Replace post/page id you want to show ratings and reviews for, it should work I guess, although I have not tried in category.php.

  • I am not very fluent with php and I am having a heck of a time adding your code to my existing site.

    The first part of your code I have tried adding to the file “wp-customer-reviews.php” and I have also tried adding it to both my single-page and single-post template files in my wordpress theme.

    No matter where I have tried to place the code I get the same results. Also if I don’t place the first block of code at all, I also get the same results. The results are as follows:

    Anywhere I place the second piece of code you gave under “To show aggregate ratings in star form, simply add this:” returns the same result of always displaying 5 stars no matter what the ratings are and even if there are no ratings.

    Anywhere I place the third piece of code you gave under “For displaying it as,” Give me the results of “Overall: stars for reviews.” but never displays any numbers.

  • Okay I finally figured out where to put the code, but it only works if I manually add the post/page id. Its also fairly useless to me until I figure this out because I can’t exactly manually add posts/pages when the posts/pages are using template files.

    Any suggestions for me?

    The real problem seems to be that I am using the plugin on pages only, not posts and i have dozens of pages. In fact to even get the plugin to work with my install I had to manually add to my template files because the plugin wouldn’t recognize my pages.

    Any suggestions for me?

    • You don’t need to add page id manually if you want to show ratings on the same page. There will be already postID in the object which you can assign, it should be dynamic.

  • In what file must the code be placed?

    • anywhere, just don’t forget to assign post/page id (for which you want to show ratings) to $pId

      • thanks for your quick response.

        What do you mean by ‘anywhere’?
        in content.php? menu.php? Something else?

        • By anywhere, i mean anywhere. it must be PHP file and the WP customer review plugin must be enabled ofcourse.

          We are just querying the DB table, which is available for all php files (header, menu, content, footer, sidebar, etc.), just you need to pass the proper post/page id, that’s it!

  • Thanks for this code.
    However I got a little problem I can’t seem to solve.
    The variables are empty ($total_reviews, $aggrerate_rating & $max_rating)

    When I run the code in phpmyadmin everything works fine.

    I’m trying to get this to work in single.php

    • Just make sure $pId has value of your post/page id. I guess it doesn’t. You can even echo the whole query and run it in phpMyAdmin. If it has the id, print_r the $row to check if anything is retrieved, if not then you need to pass the post/page id in order to work.

  • I’m having trouble adding this code. I copied and pasted the code into page.php, but nothing showed up. I tried changing the $pId line to read

    $pId = $post->9;

    because the page ID # is 9. Is this correct? Should I also add before and after the code?

    • Veronica, it’s incorrect. The $pId should be 9 and not $post->9;
      In short, replace $pId = $post->9;, with $pId = 9;
      Let me know if you still face the problem.

      • Thank you! I put this into one of the php files for the theme I’m using, but now the code is showing up on the screen, and not only on pId9 but on all pages. Any idea why?

        • You need to give some condition that will identify on which page you want to show it.

  • Hey Kalpesh,

    First of all thanks for all the great work that you have done for fixing this issue.

    Could you please give an example in code for a condition that Veronica could set? For example,

    $pId = 9 XXXXXXXXXXXXXXXXXXXXXXXXXXXX

    Sorry I have been banging my head against this for a while now. I am really just trying to get the “count” to work and am having a ton of trouble.

    Thanks in advance, any help is appreciated!!!!!

    • Thanks Ryan.
      Although I don’t know where and how you want this code to show effect, this post will definitely help you in understanding conditions to set http://codex.wordpress.org/Conditional_Tags

  • Thanks for your work making this but
    I’m lost, I installed main code in wp-customer-reviews.php

    I insert

    1
    
    %" class="average"> Reviews

    it shows 5 empty stars and the text reviews (it has one review on page with 4 stars)

    the second code (pasted in html mode) shows exactly this;
    echo “Overall: ” . $aggregate_rating . ” stars for ” . $total_reviews . ” reviews.”;

    I thought if I used code on same page as revews I don’t have to change anything?
    Is there an error in the second code?

    • You don’t need to insert this code in wp-customer-reviews.php, you have to put it in single.php or wherever you want to show this output.

      In the second code, just check if you have correct double quotes. As said, you don’t have to put the code in reviews page, you have to put it in post page with correct post/page id.

      HTH

  • Dont know what all the fuss is about, I just put the first part of the code right at the top of my brand-category.php
    and then put the 2nd part above my current WPCR echo’d shortcode, and it works perfectly! THANK YOU VERY MUCH!

    I think some people might be getting it wrong by not enclosing the code php tags…

  • Hi,

    i have 2 questions:

    1.)

    i have around 100 business names , each on a different “post” and the plugin is installed.

    i want to pull the overall rating of each business name into a table which is on a separate “page”. Each overall rating will be in a separate cell of the table.

    How will i do that?

    Do i have to put all the post IDs ?

    i am lost within the codes :(

    2.) And i want to display the overall rating of a business name at the top of the same post as stars

    ::::::::::::::::::::::::::::::

    And i am thinking it would be easier if there is a way to do these with shortcodes.

    • You need to provide the post’s ID in order to get overall/average rating for that post. You need not worry about total business names you have for each post, it will automatically be taken care once you provide the post’s ID. Please read the post for how to do it.

  • Hi,

    I have used your code to display star ratings on a page that displays a list of properties and it works, however I wanted to use the stars and I used the code you provided however it doesn’t matter what the rattings are I see 5 orange stars (even if the ratings are 2 stars etc.) I hope you can help.

    • Sorry worked it out, was a copy and paste error. All fixed now.

      • Great!

    • Hi Steve

      You commented that you are using the customer reviews code for a properties overview page. I am using for the same, I am using WP Property are you?

      How did you get it to work

      Thanks

      Paul

  • Thanks, its working for me, I was getting struggle since one week. Great dude

  • One of the problem with this code can be Table Prefix: in Kalpesh’s code it’s wp_ (wp_wpcreviews). To check your table prefix open wp-config.php and find the code:
    $table_prefix
    For example my table prefixe is $table_prefix = ‘wrd_’; and i changed wp_wpcreviews to wrd_wpcreviews
    Hope it will help someone.

  • Nice tutorial thanks very much.
    Just one issue, i wanted to use this so that the stars/rating would show up on Google search pages under my site. Using the rich snippet testing tool it doesn’t show for any pages other than the review pages itself (which it did already).

    Any way to correct this?

    Thanks in advance.

  • Hi, kalpesh

    thank you so much for your snippet which works like a charm !

    Is it possible to display only one decimal instead of 4 ? like 3,0 instead of 3,0000

    thank you so much !

    • This worked for me:

      echo "Overall: " . (round ($aggregate_rating,1)) . " stars for " . $total_reviews . " reviews.";

      “1″ being the decimal value in tenths, “2″ would be thousandths and so on.

  • Nice contribution Kalpesh,

    I’m having an issue with the output I’m hoping you can help. I have 3 test reviews posted and it just echos “Overall: stars for 0 reviews”. I’m using it for a multisite install so I’m wondering if there might be an issue there. I changed wp_wpcreviews to the specific network site wp_4_wpcreviews with no luck, I get the same result when using the star version as well.

    • Don’t know why you are getting empty results. I would suggest you to run this query in phpMyAdmin or mysql console directly to see if it fetches any records or not.

      1
      
      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

      Make sure you replace $pId with your post/page ID, wp_wpcreviews with your table name.

      • I had a similar problem … when i looked in my database I discovered the wp_wpcreviews table had no entries. It’s also a multi-site install and I solved it by creating the table ‘wp_2_wpcreviews’ (where 2 was the number of my site) as per these instructions.

        refer http://wordpress.org/support/topic/heres-a-fix-for-multisite?replies=10

        Skip step 1 as I believe it refers to an older version of WP Customer Reviews so …

        Open up your database manager in PHPmyAdmin
        Navigate to your wp_wpcreviews table (click on it)
        Click the export tab – leave the settings default and make sure it exports to SQL code
        Copy this code
        Go back to the main part of your database
        Click the SQL tab
        Paste the code into the box
        MAKE SURE YOU CHANGE the table name from wp_wpcreviews to wp_2_wpcreviews (where 2 is the number of the site you want it installed in)
        You can repeat this step (changing the site number) for multiple sites on your wordpress install that you want this to work on

  • I can see the output in phpMyAdmin. It shows the total, aggregate_rating and max_rating values after I run the query. I tried using the page id as well as just leaving it $post->ID, still shows 0. I get the same results when trying it on other sites with their own child themes in the network.

    • If you query returns the results, then it should get assigned to the variables and display it. Don’t know why it’s not showing for you. Try giving some static post or page ID (e.g. 9) instead of $post->ID if it works or not, then the problem should be $post->ID is going null/empty.

      • I’m not sure exactly but I think It had something with the quote delimiters, I changed them to the non-directional versions thinking they might have been smart quotes. I just copy and pasted the original snippet again and all is well. I appreciate the prompt help just the same, thank you!

  • hi i am trying to implement this code in the home page i was doing

    but only gives me this Overall: stars for 0 reviews.

    been trying to change the post id but same result

  • Is it possible to turn this into a shortcode? To make it available in posts/pages & widgets? That would be great if there was such a function.

  • I have reviews on the same post that the products, and also reviews that are on a different pages that the products. I don’t know how to write yout code to make it work. I do not know any php so the above instruction are not clear for me. is it something like this?
    $pId = $post->ID;
    $pId = $post->ID = 9;
    $pId = $post->ID = 10;
    Could you give an example on how to write it?

    Does it mean also that each post/page ID has to be added manually to the code each time a new product with review is added to the site if it is not on the same post?

    Is there a way to display the stars where we want to like a shortcode?

    Thanks

  • Hi KALPESH,

    I am fairly new to these things.
    Would be nice if you could tell me where i should be placing these codes?
    Thanks!

    • That depends on where you want it to appear. I placed it in single.php file, just after the title h2 tag.

      • Hi Kalpesh,

        Thank you for the quick response!

        A quick question :

        The review shows 5 stars and i believe it’s wrong. You have mentioned that you have to “FORMAT PHP” tags. How can i go about it?
        Also, i tried using the overall rating like 4.67 stars our of 60 reviews . It does not seem to work . I applied the code directly after the H1 tag as you mentioned.

        Sorry to bother you with so many questions . I am a newbie :)

  • No matter in which PHP file I place the code you provided, it always just shows up as plain text hardcoded on the page itself. This plugin is really simple and easy to use, but not being able to aggregate reviews takes away a large point of having reviews in the first place.

    Can you think of why this might be happening? Thanks!

  • works perfectly, thanks alot

    Klaus

  • Hi Kalpesh

    I’m sure you are getting tied of these questions by now but I’ve hit a wall and I too need your help.

    I am working on a property rentals site, I have WP Customer Reviews on each property page, as a shortcode inside a tab shortcode. I am using WP Property, which comes with a property overview template (property-overview.php) I have inserted the 1st code in this php file and the star form code under it. You will see I’ve used page 385, which is one of the single property pages where I have WP Customer reviews. If you have a look at the property overview page (Destinations>England) you will see the star form and count on each property but of course they are all the same ie page 385.

    How do I get the property overview page to show correct rating for each property.

    Regards

    Paul

    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;
    $wpdb->flush();
    ?>

    <div style="width: %” class=”average”> Reviews

    • Hi Paul,

      For each property (which will have have unique ID) you have to change $pId to that property’s ID to get correct reviews and ratings. So in one page you can display multiple property ratings by just changing the page_id value with the property’s ID in the SQL query.

      • Thanks for responding so quickly,

        I have the SQL query and the code for showing in star form in the property-overview.php (template for showing a list of properties via a shortcode inserted into a page) How do I call the star rating from the single-property.php for each property

        For my use, should the SQL query and the star form code be in the property-overview.php ?

        Paul

        • You need to find the file which shortcode is calling to display all the properties. You will definitely find while or for loop inside that file to display list of all properties, just put the whole code INSIDE that loop changing just the $pId to the looped propertie’s ID.

          • Appreciate your codes, but had real trouble making them work as a newbie…is it possible to have an detailed step by step instruction with screenshots, or a video (youtube), which will be very helpful, you might need 10 minutes to have this done, but that will save hundreds of people’s hours, plus, I am sure that way will attract more people coming to your web looking for help….imagine there are almost 150,000 downloads for this plugin now, and you can also imagine about half of them would like to have the aggregated rating, if they are easy enough…i would do this if I know better codes

  • For star Rating using javaScript :

    Very Simple for aggrigate:

    $(function() {
    $(‘input[type=submit]‘).click(function() {
    $(‘p’).html(”+parseFloat($(‘input[name=amount]‘).val())+”);
    $(‘span.stars’).stars();
    });
    $(‘input[type=submit]‘).click();
    });

    $.fn.stars = function() {
    return $(this).each(function() {
    $(this).html($(”).width(Math.max(0, (Math.min(5, parseFloat($(this).html())))) * 16));
    });
    }

    span.stars, span.stars span {
    display: block;
    background: url(http://www.ulmanen.fi/stuff/stars.png) 0 -16px repeat-x;
    width: 80px;
    height: 16px;
    }

    span.stars span {
    background-position: 0 0;
    }

    2.4618164

  • I have a lot of questions in my but I was able to figure out how to display it! Thanks for all the comments and support with this article and codes. THanks kalpesh !!!!! !!

  • Can anyone share the detailed procedure as I can not make it work after trying many hours as a newbie…can you help answer the following questions:

    To show the average score on PAGEs under page title only

    1. with the above codes, do we need to modify?

    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;
    $wpdb->flush();

    2. which php file needs to paste in, and where?

    i think we need to paste in the page.php file…..where do I need to put the above code if want to show the average score under the title

    3. where need to put the second part of code, what is the format??

    echo “Overall: ” . $aggregate_rating . ” stars for ” . $total_reviews . ” reviews.”;

    Thanks,

    • Got it worked, because of the $table needs to be changed, also close the first part codes with , still trying how to show one page’s average on another page…., said using ID, but seems not clear to me…what need to put in the pages…can people help, thank you

      • Hi Dave, the ID is the page’s primary ID ( you can get this from wordpress admin > pages > individual page > see the address bar with post=xxx, where xxx is the ID you are looking for )
        So if you are in Page X and want to show Page Y’s reviews, you can use the above code with $pId the value of Page Y’s.

        • Hello Kalpesh,

          Thank you for your prompt reply…it seems i know the logic, but does not know how to make it work…I put the code into PAGE.PHP with closing tag, and now I see the aggregated scores, it is correctly counted, but it appears on every page….I know if I put the page ID within the code, all pages would be that page’s score…

          I need to work on two things now: one is how to display average score only on the pages (one category) I need; another is how to display these scores in a table in another separated summary page?

          For example: one page 1, score is 4.0; page 2 score is 4.5 and page 3 score is 4.8…..about 100 pages;

          On the summary page, i want them show in the a table:

          page … average #of review

          page1 … 4.0 #of review
          page2 … 4.5 #of review
          page3 … 4.8 #of review
          ……
          page1 … 4.0 #of review

          Can I buy you a coffee help me figure out:) I really have trouble for this and need help, thank you,

          David

  • I was able to get your code to work for a technician review page where it shows the ratings for about 20-25 service technicians. My next goal is to now take the highest rated technician and display them on my home page. So that way any technician that has the highest aggregate rating (not most reviews) will appear in a section on my home page.

    Do you have any tips?

  • Can you please send me the tips? I am kind of new but really want to display many of my pages’ ratings on another single page, if possible, my email is htpsych at yahoo.com, thank you so much!

    • This is only how I got it to work. There may be a better way, but This is how I got to work what you are asking for. This was obviously done after installing the Customer Reviews plugin.

      1.On the top of the single page where you want to display the ratings for all the pages place the following code for each page where there is a rating (The comment “PAGE1″ is just for reference and change the $pId = PAGEID to reflect the page ID that you wand to display). You’ll need to do this for every page you want to disply rating for on the single page, a seperate snippet for each page:

      get_results(“SELECT COUNT(*) AS `total`,AVG(review_rating) AS `aggregate_rating`,MAX(review_rating) AS `max_rating` FROM o1lanj_wpcreviews WHERE `page_id`= $pId AND `status`=1″);
      $max_rating = $row[0]->max_rating;
      $aggregate_rating = $row[0]->aggregate_rating;
      $total_reviews2594 = $row[0]->total;
      $totl2594 = $aggregate_rating * 20;
      $wpdb->flush();
      ?>

      2.After you have the above code for each of the pages you wish to display on your single page, place the following code to display the stars and ratings #’s for each (replace PAGEID with the pages ID):

      %” class=”average”> Reviews

      3. Now finally on the top of each page where there is an option to give a rating, I placed the following code:

      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;
      $wpdb->flush();
      ?>

      You may need a plugin to place PHP in the wordpress text editor, there are a few that allow you to do this and one specifically, Insert PHP allows you to do this by replacing the tags with [insert_php] [/insert_php].

      • For some reason parts of the snippets got cut off…

        Part 1.

        1
        2
        3
        4
        5
        6
        7
        
        get_results("SELECT COUNT(*) AS `total`,AVG(review_rating) AS `aggregate_rating`,MAX(review_rating) AS `max_rating` FROM o1lanj_wpcreviews WHERE `page_id`= $pId AND `status`=1");
        	$max_rating = $row[0]->max_rating;
        	$aggregate_rating = $row[0]->aggregate_rating; 
        	$total_reviewsPAGEID = $row[0]->total;
        	$totlPAGEID = $aggregate_rating * 20;
        	$wpdb->flush();
        ?>

        Part 2.

        1
        
        <div style="width: %" class="average"> Reviews

        Part 3.

        1
        2
        3
        4
        5
        6
        7
        8
        
        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;
        $wpdb->flush();
        ?>
  • Great, thank you so much, i will give a try shortly:)

  • Thank you Very Much Sir.

    Its very useful for me. because their plugin developer did’t define such kind a process.

    Thanks a lot

  • I’ve put the code in wp_customer_reviews.php and the second in the sidebar widget for text and HTML. It shows up and is giving me 5 yellow stars, but thats not right because of the variety in ratings. Also it doesn’t count the total of the submitted reviews!

    What is going wrong??

Leave a comment

 

Welcome to my Blog

This blog is merely to record the things that I find interesting. It can be technical, humor, news, creative or anything that deserves to be posted here. Enjoy the blog and don't forget to throw comments and likes/+1's/tweets on posts you like. Thanks for visiting!

Certifications

Alexa Rank