Star ratings are a quick and simple way to get feedback from your users, that’s why it has become so popular all around the web. Today we’ll extend WordPress comments by adding our own star rating system.
The main plugin file
Let’s create the main file that will contain most of our plugin’s code. Using an FTP client navigate to /wp-content/plugins/ in your WordPress installation and create a folder called ci-comment-rating (or anything else you prefer). Next enter the folder and create a file called ci-comment-rating.php (again, naming is up to you).
Edit the file and paste in a header similar to the one below:
<?php
/*
Plugin Name: CI Comment Rating
Description: Adds a star rating system to WordPress comments
Version: 1.0.0
Author: The CSSIgniter Team
Author URI: https://cssigniter.com/
*/
Plugin header
Creating the rating interface.
First we will need to create the interface which the visitor uses to rate our post. To do that paste the code below in the plugin’s file.
//Create the rating interface.
add_action( 'comment_form_logged_in_after', 'ci_comment_rating_rating_field' );
add_action( 'comment_form_after_fields', 'ci_comment_rating_rating_field' );
function ci_comment_rating_rating_field () {
?>
<label for="rating">Rating<span class="required">*</span></label>
<fieldset class="comments-rating">
<span class="rating-container">
<?php for ( $i = 5; $i >= 1; $i-- ) : ?>
<input type="radio" id="rating-<?php echo esc_attr( $i ); ?>" name="rating" value="<?php echo esc_attr( $i ); ?>" /><label for="rating-<?php echo esc_attr( $i ); ?>"><?php echo esc_html( $i ); ?></label>
<?php endfor; ?>
<input type="radio" id="rating-0" class="star-cb-clear" name="rating" value="0" /><label for="rating-0">0</label>
</span>
</fieldset>
<?php
}
The code above will take care of placing the rating system in the comment form, for both logged in and logged out users. This is what you it will look like after you add the code:
Not very pretty, right? Let’s fix that.
Adding some styling
We will need some stars, after all it’s a star rating system, so we will need to enqueue dashicons on the frontend as well. Along with that we will need to create an assets folder in the plugin’s main folder and inside it create a style.css file. Edit the style.css file and paste in the code below.
.comments-rating {
border: none;
padding: 0;
margin-left: 0;
}
.comments-rating label {
display: inline-block;
}
.rating-container {
font-size: 0;
display: flex;
justify-content: flex-end;
flex-direction: row-reverse;
}
.rating-container * {
font-size: 1.4rem;
}
.rating-container > input {
display: none;
}
.rating-container > input + label {
/* only enough room for the star */
font-family: 'dashicons';
display: inline-block;
overflow: hidden;
text-indent: 9999px;
width: 1em;
white-space: nowrap;
cursor: pointer;
margin: 0;
}
.rating-container > input + label:before {
display: inline-block;
text-indent: -9999px;
content: "\f154";
color: #888;
}
.rating-container > input:checked ~ label:before,
.rating-container > input + label:hover ~ label:before,
.rating-container > input + label:hover:before {
content: "\f155";
color: #e52;
text-shadow: 0 0 1px #333;
}
.rating-container > .star-cb-clear + label {
text-indent: -9999px;
width: .5em;
margin-left: -.5em;
}
.rating-container > .star-cb-clear + label:before {
width: .5em;
}
.rating-container:hover > input + label:before {
content: "\f154";
color: #888;
text-shadow: none;
}
.rating-container:hover > input + label:hover ~ label:before,
.rating-container:hover > input + label:hover:before {
content: "\f155";
color: #e52;
text-shadow: 0 0 1px #333;
}
.comment-respond .rating-container > .star-cb-clear + label, .comment-respond .rating-container > input + label:before {
text-indent: 9999px;
}
.comment-respond .rating-container > input + label {
text-indent: -9999px;
}
Next go back to the ci-comment-rating.php file and paste this in:
//Enqueue the plugin's styles.
add_action( 'wp_enqueue_scripts', 'ci_comment_rating_styles' );
function ci_comment_rating_styles() {
wp_register_style( 'ci-comment-rating-styles', plugins_url( '/', __FILE__ ) . 'assets/style.css' );
wp_enqueue_style( 'dashicons' );
wp_enqueue_style( 'ci-comment-rating-styles' );
}
We start by registering the style.css file we created earlier, then we enqueue both the dashicons and the stylesheet. Now let’s save and refresh the page.
Ah, much better!
Saving the user’s input
We have successfully created the interface the user can use to rate our post, next we need to make sure the rating is stored in our database. To do that we will use add_comment_meta to create a custom field in the comments which will store our rating data. Paste the code below in the plugin’s main file.
//Save the rating submitted by the user.
add_action( 'comment_post', 'ci_comment_rating_save_comment_rating' );
function ci_comment_rating_save_comment_rating( $comment_id ) {
if ( ( isset( $_POST['rating'] ) ) && ( '' !== $_POST['rating'] ) )
$rating = intval( $_POST['rating'] );
add_comment_meta( $comment_id, 'rating', $rating );
}
In the code above we hook into comment_post which fires exactly after a comment is submitted. We check to see if the user added a rating, sanitize it, and store it in the database.
Making the rating required (optional)
If you want to have the users always submit a rating along with their comments you can paste this in the plugin’s main file.
//Make the rating required.
add_filter( 'preprocess_comment', 'ci_comment_rating_require_rating' );
function ci_comment_rating_require_rating( $commentdata ) {
if ( ! is_admin() && ( ! isset( $_POST['rating'] ) || 0 === intval( $_POST['rating'] ) ) )
wp_die( __( 'Error: You did not add a rating. Hit the Back button on your Web browser and resubmit your comment with a rating.' ) );
return $commentdata;
}
Here we check if there is a rating in the submitted comment’s data, and if not we output an error prompting the user to go back and resubmit along with a rating. This is of course optional.
TIP: if you don’t want to make the rating required consider removing the
<span class="required">*</span>
bit from the rating interface above. This will remove the visual cue that rating is required.
Display the rating on a submitted comment
Once a user has rated our post we should display that rating along with their comment. To do that paste the code below in the plugin’s main file.
//Display the rating on a submitted comment.
add_filter( 'comment_text', 'ci_comment_rating_display_rating');
function ci_comment_rating_display_rating( $comment_text ){
if ( $rating = get_comment_meta( get_comment_ID(), 'rating', true ) ) {
$stars = '<p class="stars">';
for ( $i = 1; $i <= $rating; $i++ ) {
$stars .= '<span class="dashicons dashicons-star-filled"></span>';
}
$stars .= '</p>';
$comment_text = $comment_text . $stars;
return $comment_text;
} else {
return $comment_text;
}
}
What we do here, is hook into comment_text, check if there is an actual rating on the post, if there is we generate some markup that will display it and return it along the comment’s text. If there is no rating we just return the comment’s text.
Job done!
That’s pretty much it, we have created a simple plugin that will add a star rating system on WordPress comments.
Extending the plugin
Now that you have the data, you can utilize it in any way you wish by extending the plugin a bit. For example let’s get a post’s average rating and display it above the content.
In the plugin’s main file paste this in.
//Get the average rating of a post.
function ci_comment_rating_get_average_ratings( $id ) {
$comments = get_approved_comments( $id );
if ( $comments ) {
$i = 0;
$total = 0;
foreach( $comments as $comment ){
$rate = get_comment_meta( $comment->comment_ID, 'rating', true );
if( isset( $rate ) && '' !== $rate ) {
$i++;
$total += $rate;
}
}
if ( 0 === $i ) {
return false;
} else {
return round( $total / $i, 1 );
}
} else {
return false;
}
}
This function will get the ID of a post, run through all of the approved comments, sum up the existing ratings and return the average rounded up to the first decimal. If there are no ratings on the tested post it will return false.
To display the average comment rating above the post’s content we can use this code:
//Display the average rating above the content.
add_filter( 'the_content', 'ci_comment_rating_display_average_rating' );
function ci_comment_rating_display_average_rating( $content ) {
global $post;
if ( false === ci_comment_rating_get_average_ratings( $post->ID ) ) {
return $content;
}
$stars = '';
$average = ci_comment_rating_get_average_ratings( $post->ID );
for ( $i = 1; $i <= $average + 1; $i++ ) {
$width = intval( $i - $average > 0 ? 20 - ( ( $i - $average ) * 20 ) : 20 );
if ( 0 === $width ) {
continue;
}
$stars .= '<span style="overflow:hidden; width:' . $width . 'px" class="dashicons dashicons-star-filled"></span>';
if ( $i - $average > 0 ) {
$stars .= '<span style="overflow:hidden; position:relative; left:-' . $width .'px;" class="dashicons dashicons-star-empty"></span>';
}
}
$custom_content = '<p class="average-rating">This post\'s average rating is: ' . $average .' ' . $stars .'</p>';
$custom_content .= $content;
return $custom_content;
}
The code above will try to get the average rating using the function we created on the previous step, if it doesn’t get anything it will just return the content, otherwise it will place a paragraph, just above the post’s content, displaying the average post rating.
Wrapping up
That’s all for this tutorial, we hope you found it useful and if you come up with interesting ideas of extending the plugin and using the gathered data, please let us know in the comments below!
The complete plugin file
Below you will find the entire ci-comment-rating.php file which you can copy/paste into your plugin folder.
<?php
/*
Plugin Name: CI Comment Rating
Description: Adds a star rating system to WordPress comments
Version: 1.0.0
Author: The CSSIgniter Team
Author URI: https://cssigniter.com/
*/
//Enqueue the plugin's styles.
add_action( 'wp_enqueue_scripts', 'ci_comment_rating_styles' );
function ci_comment_rating_styles() {
wp_register_style( 'ci-comment-rating-styles', plugins_url( '/', __FILE__ ) . 'assets/style.css' );
wp_enqueue_style( 'dashicons' );
wp_enqueue_style( 'ci-comment-rating-styles' );
}
//Create the rating interface.
add_action( 'comment_form_logged_in_after', 'ci_comment_rating_rating_field' );
add_action( 'comment_form_after_fields', 'ci_comment_rating_rating_field' );
function ci_comment_rating_rating_field () {
?>
<label for="rating">Rating<span class="required">*</span></label>
<fieldset class="comments-rating">
<span class="rating-container">
<?php for ( $i = 5; $i >= 1; $i-- ) : ?>
<input type="radio" id="rating-<?php echo esc_attr( $i ); ?>" name="rating" value="<?php echo esc_attr( $i ); ?>" /><label for="rating-<?php echo esc_attr( $i ); ?>"><?php echo esc_html( $i ); ?></label>
<?php endfor; ?>
<input type="radio" id="rating-0" class="star-cb-clear" name="rating" value="0" /><label for="rating-0">0</label>
</span>
</fieldset>
<?php
}
//Save the rating submitted by the user.
add_action( 'comment_post', 'ci_comment_rating_save_comment_rating' );
function ci_comment_rating_save_comment_rating( $comment_id ) {
if ( ( isset( $_POST['rating'] ) ) && ( '' !== $_POST['rating'] ) )
$rating = intval( $_POST['rating'] );
add_comment_meta( $comment_id, 'rating', $rating );
}
//Make the rating required.
add_filter( 'preprocess_comment', 'ci_comment_rating_require_rating' );
function ci_comment_rating_require_rating( $commentdata ) {
if ( ! is_admin() && ( ! isset( $_POST['rating'] ) || 0 === intval( $_POST['rating'] ) ) )
wp_die( __( 'Error: You did not add a rating. Hit the Back button on your Web browser and resubmit your comment with a rating.' ) );
return $commentdata;
}
//Display the rating on a submitted comment.
add_filter( 'comment_text', 'ci_comment_rating_display_rating');
function ci_comment_rating_display_rating( $comment_text ){
if ( $rating = get_comment_meta( get_comment_ID(), 'rating', true ) ) {
$stars = '<p class="stars">';
for ( $i = 1; $i <= $rating; $i++ ) {
$stars .= '<span class="dashicons dashicons-star-filled"></span>';
}
$stars .= '</p>';
$comment_text = $comment_text . $stars;
return $comment_text;
} else {
return $comment_text;
}
}
//Get the average rating of a post.
function ci_comment_rating_get_average_ratings( $id ) {
$comments = get_approved_comments( $id );
if ( $comments ) {
$i = 0;
$total = 0;
foreach( $comments as $comment ){
$rate = get_comment_meta( $comment->comment_ID, 'rating', true );
if( isset( $rate ) && '' !== $rate ) {
$i++;
$total += $rate;
}
}
if ( 0 === $i ) {
return false;
} else {
return round( $total / $i, 1 );
}
} else {
return false;
}
}
//Display the average rating above the content.
add_filter( 'the_content', 'ci_comment_rating_display_average_rating' );
function ci_comment_rating_display_average_rating( $content ) {
global $post;
if ( false === ci_comment_rating_get_average_ratings( $post->ID ) ) {
return $content;
}
$stars = '';
$average = ci_comment_rating_get_average_ratings( $post->ID );
for ( $i = 1; $i <= $average + 1; $i++ ) {
$width = intval( $i - $average > 0 ? 20 - ( ( $i - $average ) * 20 ) : 20 );
if ( 0 === $width ) {
continue;
}
$stars .= '<span style="overflow:hidden; width:' . $width . 'px" class="dashicons dashicons-star-filled"></span>';
if ( $i - $average > 0 ) {
$stars .= '<span style="overflow:hidden; position:relative; left:-' . $width .'px;" class="dashicons dashicons-star-empty"></span>';
}
}
$custom_content = '<p class="average-rating">This post\'s average rating is: ' . $average .' ' . $stars .'</p>';
$custom_content .= $content;
return $custom_content;
}
177 responses to “Add ratings to the WordPress comment system.”
You are the Best!!!
I spend so much time on pointless Plugins to do exactly what you’ve created. And then I found your Article from nowhere and works PERFECTLY…..Thank you for doing what you do and we – the people who are still learning – learning from people like you. I know I made you like a God but I’ve spend so much time on shitty Plugins and I’m really happy now…Thank you again :) :)
excellent !
Hi Nik, how do i create a general/universal rating and create short-code to include in custom post types ?
thank you very much !
Hello Dee!
The rating system is very simple, which, luckily, makes it universal. Any post type with a comments template will have the rating available. So if you have a custom post type that does not have comments, just edit the post type’s single template, add the comments template and you should be good to go.
If you are getting an error with the
wp_register_style( ‘ci-comment-rating-styles’, plugins_url(/,__FILE__) . ‘assets/style.css’ );
line on ci-comment-rating.php, changing the whole line to:
wp_register_style( ‘ci-comment-rating-styles’, plugins_url() . ‘/ci-comment-rating/’ . ‘assets/style.css’ );
may fix it for you.
Hello! This works perfectly. I would like to extend the plugin further by displaying the total number of reviews used to calculate the average, and have tried a new function but am calculating something greater than the total number.
For example, an average rating of 3.5 might use a total of 2 or 2,000 reviews. I’d like to output that part to add context to the rating. Thank you!
Hello there!
Glad to hear you found the post useful. Please check out this gist to implement the functionality you want.
Specifically all changes have been done in the last two functions. ci_comment_rating_get_average_ratings was replaced by ci_comment_rating_get_ratings_data which now returns an array of the total number of reviews and their sum. ci_comment_rating_display_average_rating was modified to use that data to calculate an average and display the number of reviews used to get that average.
Hope this helps!
Unfortunately, this doesn’t work for comment replies.
Thank you for noticing!
It was a styling issue due to the way WordPress handles comment replies. I have updated the styles in the style.css file and it should be ok now. Grab lines 77-83 from the style.css above and paste them in your existing one. That should do the trick.
This post is now 7 months old and doesn’t appear to work anymore? I’m getting this error when trying to activate it: “Parse error: syntax error, unexpected ‘/’ in /var/www/vhosts/72brain.com/httpdocs/wordpress/wp-content/plugins/ci-comment-rating/ci-comment-rating.php on line 14”
Looks like you need quotation marks around the / on line 14.
plugins_url(/,__FILE__
should be
plugins_url(‘/’,__FILE__
Hello Tim.
I’m not really sure as to why you got an error.
If you check the code above you will see that the quotation marks are there, and they were there since the beginning.
The error is on line 14 inside “The complete plugin file”
We did copy paste the whole thing and there it is :)
Hello Nacho. Did you by any change use Firefox when copying the plugin code? Because Firefox had an issue displaying the code properly. Please try copying from this gist and let me know if there’s a difference. https://gist.github.com/nvourva/08ef63220a48ff80827a71af132ef6bf
Such a Nice Plugin and cleverly made Nik. You are Awesome.
But what i need is i want to make this one can be rate by guest users (outside comments section). This should be at the end of the post where every visitor can rate this. Also if it can show total no. of ratings made and overall average rating then would be great.
Once you help me with this will post entire updated code as i have implemented some schema structured within code for SEO
Regards
Sachin G.
Hello Sachin.
Glad to hear you like the plugin. What you are looking for is a completely different plugin, you can try having a look at GD Rating or any other post rating plugin on the WordPress plugin directory to help you achieve your goal.
Hi Nik,
I like this solution a lot! It works like a charm and is much lighter than all other full-blown rating solutions for WordPress.
One single thing would be great: is there a chance for a non-development guy like me to display the average rating on any other place? I’d like to include it in a big header image and by now I can only display the rating directly above the content.
Hello Heiko.
I’m happy to hear you find this small plugin useful.
Regarding to your question, I’m afraid there is no easy way to do that without some development background. The output is now hooked to the post’s content, what you would need to do is unhook it from there and hook it to your theme’s header to overlay it on an image, however this requires your theme to have a hook on the header, if not one needs to be added there.
You can add the function in your header.php file to display the average echo ci_comment_rating_display_average_rating();
Thank you very much, awesome plugin!
Hi there,
Improvement suggestion: Instead of calculating the average rating on each post view, saving it in a custom field would be more efficient (once lots of comments with ratings are used).
Cheers,
Thomas
This is a great suggestion Thomas. Indeed it would be better performance-wise if the value was stored instead of being calculated on the fly.
What we aimed to create was a base for a commenting system on which users could built-upon using their improvements, so we kept it pretty basic, simple and functional. If it where to become a full fledged plugin, it goes without saying that storing the value is better.
Hi! I’m trying to add microdata to ratings and this function would be very helpful. Can you at least suggest an approch for saving the average rating in a custom field?
Hello Marco. Grab the code from my gist here and use it to replace lines 37-43 on the final plugin file. This will save the average in a post meta and you will then be able to pull it using get_post_meta().
Thanks a lot. You may update the line 14 in “The complete plugin file”
It has / instead of ‘/’ which gives error and might confuse people.
Also, can this plugin work with social/disqus comments
Hello Ajay.
This is how I see line 14 on my end http://bit.ly/2OqEuCX do you see something different?
Unfortunately no, it will only work on the default WordPress comments system.
Created ci-comment-rating directory in wp-content/plugins. Clicked on directory and created file called ci-comment-rating.php. Proceeded to enter header info and php code for //Create the rating interface. Permissions set to 755
Plugin does show in WP plugins page. When I go to activate, I get “Plugin could not be activated because it triggered a fatal error.”
Also tried pasting full code listed in “The complete plugin file”. I did not create style.css because it would not make difference if plugin did not work.
Am I missing something here?
Hello John.
Since it appears you know your way around server file management, could you please check your debug log file and see if there is an entry for said error?
Thank you.
Hii there,
I just want to add custom rating symbols instead of star for a particular category.For example if the category is of food then the post inside food category will have ice cream as an rating symbol. Plz help me out.
Hello Amit.
This could be a bit tricky to implement. Our sample plugin uses icons from the Dashicons set included with WordPress. You could replace the content bits in the style.css file, i.e.
content: "\f155";
with the content for another icon, for example \f155 is for the full star icon, it could be replaced with \f511 which is a carrot. However this would be global, there is currently no way to set a different icon per post category I’m afraid.Hi there, thanks for code, i have a little proble when admin have to reply a comment.
it checks for rating in administration page.. so it is imposible for an admin to live a reply in admin page, we have to go to post and reply there and make a rating.
Is any way to not check if is rating in a post for admin only? thanks, best regards.
Hello.
Excellent observation. I have patched the plugin file, now administrators should be able to reply without adding ratings from the dashboard. Replace line 48 in your plugin file with the one found in the article’s full plugin file, it should do the trick.
many thanks, i do it like this days before..
“function ci_comment_rating_require_rating( $commentdata ) {
if ( ! isset( $_POST[‘rating’] ) || 0 === intval( $_POST[‘rating’] ) )
wp_die( __( ‘Error: You did not add a rating. Hit the Back button on your Web browser and resubmit your comment with a rating.’ ) );
return $commentdata;
}
if( !is_admin() ){
add_filter( ‘preprocess_comment’, ‘ci_comment_rating_require_rating’ );
}”
is it the same result as you wrote?
I have a bit tricky question now, i think, how to return meta rating as a query string in url for reorder posts from average? Im trying to do it, but not get results atm, hope you can help on this too.. thanks, best regards!
Glad to hear you figured this out, what you did is pretty much the same thing. For your other question, have a look a this pretty thorough guide on query variables.
Sir, thanks for providing such wonderful step-by-step tutorial for us newbie, I just wonder if I can fix the code to be able to be commented by anyone(no need to login)? and furthermore, if I can add rating star from multiple perspective, like review A, review B, review C, review D…. all with star review, thanks in advance for your tutoring~
Hello Ryan.
Glad to hear you found the tutorial helpful. Allowing people to comment without being logged in is a WordPress feature. Just navigate to Settings -> Discussion -> Other comment settings and uncheck the “Users must be registered and logged in to comment” box, that should do the trick.
Could you please explain more the second part of your question?
Thank you.
Nice job thank you !
Is it possible to do this only for custom post type by little bit modification?
Please help…
Hello Gaurav. If comments are enabled using WordPress’ default commenting system on your custom post type, the rating should just appear there without any modifications.
I have a custom post type where I want to use a comment rating system and this works just fine however I do not want the standard blog posts to have the rating system. Can this be used to use the star rating on the comments for a custom post type only and not on the default blog posts?
Hello Paul.
Sorry for this very late reply. Unfortunately due to the simple nature of the plugin it can’t be easily modified to display on specific post types I’m afraid.
Hi Nik Vourvachis,
Can you please help me out for how i can add this in author page.
example.
Author name: Manish Salunke
Post Title: First Post
Comment: 5 Star
———————-
Post Title: Second Post
Comment: 4 Star
Thank you…
Hello Manish. Unfortunately there is no such functionality built into the plugin due to its very simple nature. Adding it would require quite a lot of work which falls outside the scope of this simple tutorial I’m afraid. We are in the process of gathering feature suggestions based on your posts in order to evaluate if there is a need for a full fledged ratings plugin. Let us know if this is something that sounds interesting to you. Thank you!
Hello Nik,
Thanks for such a great code. How to get top rated posts?
Thanks
Hello Sodozai. Unfortunately there is no such functionality built into the plugin due to its very simple nature. Adding it would require quite a lot of work which falls outside the scope of this simple tutorial I’m afraid. We are in the process of gathering feature suggestions based on your posts in order to evaluate if there is a need for a full fledged ratings plugin. Let us know if this is something that sounds interesting to you. Thank you!
Hello, thank you. How do this for google rich snippet? (stars in google search result)
Hello. Unfortunately there is no easy way of doing this at the moment. You would need to store each post’s average rating as post meta and then find a rich snippet plugin that accepts and displays custom meta.
Hi Nik,
First of all thanks for the tutorial.
I have 2 questions.
1. How to show the empty star, for example in case of 4 star rating how to show 4 star filled and 1 empty star?
2. How to show the average rating within the loop?
Thanks
Hello Rahul. Regarding #1 locate line 121 in the full plugin’s file in the post and below it paste the code found in this gist http://bit.ly/2JX7Sio that should do the trick. To get the average rating inside the loop try using
ci_comment_rating_get_average_ratings
Thank you so much for this plugin. It works great and I was able to make some easy customizations.
The one thing I was wondering, however, how could I show all 5 stars on the average rating? So for example when the average rating is 3 stars it shows only the 3 filled stars and I’d like it to show 3 filled stars and the remaining 2 stars just the outlined stars to indicate it is 3 out of possible 5 stars. I hope that makes sense.
Thank you.
Hello Rob. Locate line 121 in the full plugin’s file in the post and below it paste the code found in this gist http://bit.ly/2JX7Sio that should do the trick.
Hello,
your plugin is incredibly good, light and very simple to implement, so thanks for that, however I ask you, I am not a programmer but I understand something about php, and I would like to show in some widget, or somewhere the metas [ counts comments and averaging rating ] of a specific post, just as the top of the post. My idea is in frontpage of my website, shoe posts summary with this information, average and data count of comments.
Hello Jorge. Due to the very simple nature of this plugin there is no widget functionality and the work required to add it falls outside the scope of this tutorial, I’m very sorry. We are however gathering requests for features and we are examining the possibility of bringing all of them into a full fledged plugin in the future. Let us know if you are interested in something like this.
Hey excellent!!!! any shortcode for use the average in anywhere?, can i make some like a shortcode?
Hello Milton. Due to the very simple nature of this plugin there is no shortcode functionality and the work required to add it falls outside the scope of this tutorial, I’m very sorry. However we are gathering requests for features and we are examining the possibility of bringing all of them into a full fledged plugin in the future. Let us know if you are interested in something like this.
I would love a short code as Milton requested. Would be great to display the average rating of a product in specific places with the ability to link to a main review page.
Thank you for the feedback Tony!
Hi, Is it possible to add multiple reviews and show the average of all reviews.
Hello Sandra. Currently the plugin displays the average of all user submitted ratings on a certain post.
You made it so simple! Thanks a lot!
For anyone looking for the solution on how to display the rest of the stars (eg. rating is 3 and it displays only 3 stars) you need to change the function *ci_comment_rating_display_rating*
https://gist.github.com/rwkyyy/f8997d3fdbea4bb36941ad7d4ef20064
How Can I display summary on below content?
Hello.
You can try changing lines 124 & 125 of the full plugin file above to:
$content .= $custom_content ;
return $content;
Hi Nik. Thank you, Work perfect. How if i want to display rating in other place like after the title, or post meta and the rating will display also on thumbnail post. thank you.
Hello! Glad to hear you like the plugin.
You can move the rating by utilizing a different filter from the ones here https://codex.wordpress.org/Plugin_API/Filter_Reference#Database_Reads. By default we filter the_content at line 97 of the plugin file. You can similarly filter the title, or the tags, etc to get the layout you want.
Hi, I’d like to add this star rating to my blog as I publish recipes and would get feedback by comments, but think a star rating would be so much better.
However, in addition to adding this to my blog, would there be a way to display the current rating in my blog post, directly where the recipe section is inside the post (i use recipe schema markup wrapped in div)?
Also, will Google show the average rating in the SERPs?
Thank you.
Hello Lisa.
Unfortunately this plugin does not offer the functionality you are looking for due to its very simple nature it’s meant to serve only as a tutorial which can then be expanded upon. I’m sorry.
Very very helpful tutorial
Odin Bless you buddy
Great plugin, but I noticed an unusual bug in the system. Yes, it involves line 14 again.
If you have it as wp_register_style( ‘ci-comment-rating-styles’, plugins_url(/,__FILE__) . ‘assets/style.css’ );
it simply throws an error.
However, if you do this:
wp_register_style( ‘ci-comment-rating-styles’, plugins_url(‘/’,__FILE__) . ‘assets/style.css’ );
it works, but the stylesheet doesn’t show up. Instead, I checked the code and I saw /NANassets/style.css which of course, doesn’t actually exist. So Console throws a 404.
I’d prefer using the styles and just placing them instead in main style.css but if I delete that line and actually that entire function, I get the white screen of death. So what to do?
Hello Adam.
Glad to hear you like the plugin.
Regarding the issue, can you please try replacing the plugin’s code with the one found in this gist https://1n.pm/JKBsc and let me know if things work better.
Also, I know it displays the reviews on Custom Post Types. I can vouch for that. However, is there a way just to have the reviews appear only on CPT’s and not the typical blog posts. They would just get the standard commenting system. I plan to use this to review events in the Events Calendar plugin and thus their CPT.
Hello Adam.
I’m afraid the way this example plugin is written does not allow for such separation easily. I’m sorry.
Hi Nik
This is really a fantastic plugin especially for the fastness and simplicity and covers really a useful functionality. I would like to generate a shortcode to be able to place the calc and display of the average rating in between the blocks or paragraphs on the post.
I succeded in generating the shortcode by adding at the and of the whole plugin file the following code lines:
function ci_cr_display_fn( $content ) {
$ci_cr_display = ci_comment_rating_display_average_rating( $content );
return $ci_cr_display;
}
// This adds support for a “ci-cr-display” shortcode
add_shortcode( ‘ci-cr-display’, ‘ci_cr_display_fn’ );
so wherever the shortcode [ci-cr-display] is placed the average rating is shown. What i am unable to do is to get rid of the hooked above or below average rating coming from the original function.
Please is there a way to get rid of the hooked average rating and leave at this point only the shortcode as it is working?
Many thanks in advance
hi Tommy
i just delete this “add_filter( ‘the_content’, ‘ci_comment_rating_display_average_rating’ ) ” and it work fine for me thank you
Hi Nik
Another question sorry: is it possible to give to the stars a gold colour?
Many thanks
Hi Nik
I solved all the above.
Just to let you know.
Regards
Glad to hear you have managed to fix everything Tommy :)
Nice plugin! I even managed to add additional star ratings for more criteria. the problem is, it also shows in comment replies, is there anything I can do with that?
Hello Allen. Do you have the revised code uploaded somewhere where I can take a look?
This kind of plugins really provide both user and owner with a quick review of the website and really like how easy it is to configure. Will definitely use on my site.
Hi,
How to get top rated posts based on average rating?Also i want to show average rating value with each post in admin(I’ll add a custom column for average rating).
Need complete code.
Thanks
Hello.
Unfortunately the code needed to achieve what you are looking for is quite complex and falls outside the scope of this tutorial. I’m sorry.
I want add star section on product page, how to add but star review is clickable
Hello.
If you are referring to WooCommerce products, these already have star ratings. If products are a custom post type created by the theme, or another plugin it should display ratings as long as the post type supports comments.
Hi,
Great !! It’s work fine.
Just a question…
if i don’t want to create a plugin, may i insert your code in function.php ?
Hello Mike.
You could add the code in the functions.php file, but I would not recommend doing so. The functionality provided by the snippet is plugin territory and should be treated as such.
Ok !!! thanks
last question
how can i insert the average rating in my content ?
Hi Nik,
Great plugin, thanks very much. This is exactly what I was looking for.
I do have one problem though. The star rating seems to have picked up the css file, but it’s still showing them vertically instead of horizontally as in your example. Is there a specific line of the code that deals with that please?
Thank you
Hello Paul.
This sounds like it could be a styling conflict. Is this somewhere live where I can take a look?
Hi Nik,
Sorry i’m not sure my last reply worked as I tried it via my mobile. The site is under construction but you can see a sample post here:
https://reviewmyrun.com/parkrun/bedford-parkrun/?highlight=Bedford
Thanks very much :)
Paul
Indeed it’s some styling applied by the theme.
Try adding this
#respond .rating-container label {
display: inline-block;
}
at the bottom of the rating plugin’s stylesheet.
Hi Nik,
Thanks so much – works perfectly! You’re a genius :)
Thank you again for the plugin – it’s awesome :)
Hi Nik, is it possible to call and display avg rating of an post to outside of post? lets say on homepage… thanks
Hello Edmon. Unfortunately this simple plugin does not have the ability to pull ratings outside the post. This would require some extra functionality like shortcodes which was outside the scope of this exercise. I’m sorry.
Thank you for asap reply, anyways its a nice tutorial for me :)
Hi,
Thank you so much for this plugin !
Excuse me for my stupid question, but how could we put a little more space between the frame where we select the number of stars and the button “send” or remove the frame simply … I know it comes from the CSS of the theme but I would not want to touch it … Do you have an idea?
Thank you,
Daniel
Hello Daniel.
Is there a link where we can see the issue?
Does this star rating follow the review snippet/markup guidelines by google and is shown in search results by google?
Hello Fabio.
Unfortunately no, this plugin was just a tutorial on how to implement a very basic star rating system on WordPress, it does not offer advanced features such as search engine compatible markup.
hi ,
thnku for creating such plugin
its nice
can you please tell how i peginate this comming comments
Hello.
WordPress includes comment pagination by default, to enable and use it navigate to Settings -> Discussion and enable the highlighted box shown here https://i.imgur.com/2CDIbWU.png
Set the cut-off number of comments and choose if you want the latest or older comments to appear first.
How I can allow users to select half star rating?
That’s a good question! It’ll have to be answered on a follow-up post (or an update to this one) as it’s not particularly trivial to be included in a comment. Thanks!
Hi. I only want the star form to be displayed on the WC Plugin, single product -> comment tab. What should I do?
Does not work:
function ci_comment_rating_rating_field () {
$query_args = array(
‘post_type’ => ‘product’,
);
return new WP_Query( apply_filters( ‘ci_comment_rating_rating_field’, $query_args ) );
?>
Hello.
You are probably better off using WooCommerce’s built-in review system for that. Go to WooCommerce -> Settings -> Products -> General and in the Reviews section check the Enable product reviews box.
Hello admim.
Thanks for your guide.
But, How do we can create a reply for each comment rate?
I think we make a reply for comment rating like rating of themeforest. That is great!.
I hope, admin have a guide for this function.
Thanks you.
Hello.
Unfortunately there is no easy way to achieve this through this small tutorial plugin. I’m sorry.
Works great! However I see in the database the rating is getting saved twice. You actually don’t need this function at all “ci_comment_rating_save_comment_rating”. It gets saved automatically.
Hello Brian.
Have you made any alterations to the code? I’ve made a sample installation to verify and I don’t see anything being saved twice.
How I can allow users to select half star rating? I have a custom post type where I need to utilize a remark rating framework and this works fine and dandy anyway I don’t need the standard blog entries to have the rating framework. Would this be able to be utilized to utilize the star rating on the remarks for a custom post type just and not on the default blog entries?
Hello.
Unfortunately due to the simple nature of the plugin it’s not possible to filter it out of single posts at the moment I’m afraid.
Hi! Thanks for the useful post. It’s really amazing. But I have some questions: Can I get the average rating input it into the post meta and then use it for displaying it into my post. For example: add_post_meta( $post_id, ‘av_post_raiting’, $avrating ); However, in this case, I do not understand how to correctly assign $post_id. Tell me if there is a solution.
Hello Victor.
You can modify the save_comment_rating function according to this gist in order to be able to save the average post rating in a post meta.
Hi is it possible to add the star rating on edit section of the comment
Hello.
Unfortunately due to the simple nature of this plugin it’s not possible to add the rating system to the dashboard.
Hello. I don’t know if you are still going to reply to this but how do I use it in my theme functions.php instead of using it as a plugin. Thanks.
Hello Chris.
I would not recommend integrating this code in a theme. Adding it to a theme would result in losing your changes every time the theme is updated, and missing important theme updates just to retain the rating functionality is not advisable. What this little snippet offers is primarily considered plugin functionality and that’s why it was offered as one.
Hello! Thanks for you post! This post is amazing. But I have one problem, I was add your plugin to my site. But localtion show of that is on top of post, have any way to reoder it move to bottom of post? I very need your help, thanks you so much if you can answer me!!!
Hello.
You can try replacing lines 123-125 in the final plugin file with these
$custom_content = '
This post\'s average rating is: ' . $average .' ' . $stars .'
';
$content .= $custom_content;
return $content;
to move it to the bottom.
Hello! Your code very amazing! But I want to show total have how many people was rating! How to do that in your code? I think we need fix line 193: $custom_content = ‘This post\’s average rating is: ‘ . $average .’ ‘ . $stars .”;
But I don’t know add function or anything to count sum of comment! Can you help me about that? That very improtant with me!!!
Hello.
You can change line 88 to
return array(
'rating' => round( $total / $i, 1 ),
'total' => $i
);
then change line 106 from
$average = ci_comment_rating_get_average_ratings( $post->ID );
to
$average = $this->ci_comment_rating_get_average_ratings( $post->ID )['rating'];
$people = $this->ci_comment_rating_get_average_ratings( $post->ID )['total'];
and finally change line 145 from
$custom_content = '
This post\'s average rating is: ' . $average .' ' . $stars .'
';
to
$custom_content = '
This post was rated by ' . sprintf( _n( '%s person', '%s people', $people, 'text-domain' ), intval( $people ) ) .' and got an average rating of: ' . $average .' ' . $stars . '
';
Hi Nik! This post was really helpful for me. I do have a question regarding how to add this functionality to the WordPress REST API. I use WordPress solely as a CMS and backend API – my frontend is a completely separate application. I’d like to be able to create / retrieve comments with ratings through the API. Do you have an idea of how to do that? Any help would be appreciated! I’ve been stuck on this problem for months.
Hello Bryan.
You could try registering a new rest field with the comment meta and then pull them from there.
Try something like this
register_rest_field( 'comment', 'meta_rating', array(
'get_callback' => function ( $data ) {
return get_comment_meta( $data['id'] );
}
)
);
in the backend and you should be able to see ratings in the meta_rating field of the response JSON. For more info check out register_rest_field.
Hope this helps.
How would I add this to the entry header area? On my post I currently see:
*Categories*
*Post Title*
*comment*
*this is where I’d like to add it*
It currently appears under some functions that are inserted for each post (Print, Jump to Recipe).
Hello Ben.
If the recipe related functions use the same filter as the rating display it could be that they are running later and thus get placed above it. Try adding a higher priority number to the rating’s display hook to force it to execute later and see if it helps. Change line 96 like so
add_filter( 'the_content', 'ci_comment_rating_display_average_rating', 99 );
or even higher.Hi Nik,
Great tutorial, works like a charm. One question though. Is it possible to create a half-star rating? Or maybe a hint on how to accomplish this. I would like to have a bit more refinement in user rating.
Hello Theo.
We don’t have anything ready but I can give you some pointers to get you started. In line 28 you need to change 5 to 10 to get the 10 stars required. Then you will have to fiddle with the styling with this fiddle as a guide. Once styling is done you might have to adjust the math a bit to get the right average on the result.
Hi Nik,
Sorry for the late reply.
I’ll try your suggestion. Thanks!
Hello! Thank you for this code. I was able to get my theme (which I like aesthetically but doesn’t natively support woocommerce) to display the star-rating of a product as well as submit star-rating with comments! Is it possible to move the comment box into a tab next to Description and Additional Information on the product page, or is that outside the scope of this plugin?
Thank you!
Hello Diane.
Unfortunately this simple plugin does not differentiate between different custom post types, so it’s rather complex to have it moved on a location that only exists on a certain custom post type. I’m sorry.
Hey Nik, great plugin.. Can you help me in this ? After logged in i am not able to rate.
Hello.
Are you getting any particular errors? What is the user role of the account you are logging in with?
this is more powerfull star rating than other plugins available but here i think there is one problem with average star rating for example if average rating is 3.4 than it shows 4 stars and last star is half which is great but it should show 5 stars with second last star half and last star without fill please update code snippet i really liked it if this thing done than i will add structured data to it and share it here and i think the problem is here
for ( $i = 1; $i 0 ? 20 – ( ( $i – $average ) * 20 ) : 20 );
if ( 0 === $width ) {
continue;
}
$stars .= ”;
if ( $i – $average > 0 ) {
$stars .= ”;
}
}
Hello! Glad to hear you like the plugin.
I have made some modifications to the code, have a look at this gist and let me know if it offers what you are looking for.
does not work for me. could be because of my theme?
Hello, this could be the case, if your theme hooks and modifies the content and/or comments section, this could cause the rating system not to appear.
Hello, How to creat shortcode for this function for use inside theme.
Hello.
Unfortunately making this into a shortcode falls outside the scope of this simple tutorial.
I’m sorry.
Thankyou, this is that i looking for.
i can add star rating to my product page now.
Hello and thank you for this script. By the way I cannot see any change in my comment area. (I use it on the pages).
Maybe I wrong something?
Thank you and kind regards
Filippo B
Hello Filippo.
Are comments enabled on your pages and it’s just the rating that does not appear, or comments do not show up at all?
Hello, thanks for this great plugin. I’m trying to add a line of code update_comment_meta that works to update the rating. Can you help me? thanks before
Hello.
Can you share the exact goal you are aiming for please?
hello brother,
– First: I would like to thank you for this great guide that helped me a lot.
– Second: Can I only count comments that have added a vote, and exclude comments that have not added a vote from the final rating and the number of votes.
thank you all.
Hello.
The rating system only takes into consideration posts that have a rating attached to them. Are you trying to achieve something different?
How to add rating for comments only custom post type?
Thanks!
Hello.
Due to the simple nature of this exercise there is no clear cut way to restrict the appearance of the rating system on a single post I’m afraid.
Looks good however any reason you didn’t use the WordPress core wp_star_rating function?
Hi Nik,
Wonderful piece of code.
Any idea why it keeps deactivating itself saying ‘The plugin does not have a valid header’?
Anyone else with this problem?
I’m using the code and it works, except the plugin turns itself off.
You can see the ratings live on my site by the way. Thankful for your answers.
Hello.
This could be caused by a typo in the file creation process. You could try deleting the plugin’s file and recreating it to see if it helps.
Could you tell me how I can install this script step by step
Hello.
An easy way to do this would be to create a folder on your computer named ci-comment-rating inside create a ci-comment-rating.php and paste the contents of the final plugin file. Then zip up this folder and go to Plugins > Add New in your WP dashboard, click Upload and upload the zip file you have just created.
Is it possible to use this with a custom comments form template?
Hello.
If that custom comments form template provides the appropriate hooks, it would be possible to do that.
Fantastic. You are super hero!!
Question: How do we show these ratings on google serach results??
Thank you so much for this great plugin! The feeling is super when I created it myself following your steps and code. Thank you.
Hello.
Unfortunately there is currently no simple way to add this simple rating on Google search results because this was outside the scope of the tutorial.
Best regards.
Congrats for this great plugin.
But when I upgraded the site to PHP 8.0 from PHP 7.4 I have some PHP errors that makes not possible to edit a CPT until i downgraded PHP or disactivated the plugin.
Maybe you could make compatible with PHP 8.0? It would be great.
Thanks so much for this – it has helped immensely!
I’m wondering – for me it is presenting ltr 1-5 on my android pixel 5, but it is presenting opposite 5-1 on iphone safari. Any ideas here?
I’d also like to remove the numbers from the stars once I get the order sorted.
Feel free to email me for the url (info [at] nfwebsites [dot] com
Thanks for your help!!
Hello Natasha.
Thank you for bringing this to my attention. I have updated the styles for the rating-container. Safari should be ok with these new ones.
Hello Nik, thanks a lot this might just solve my problem, how do i use it with the rest api? thanks again
Hello!
Glad to hear you like our simple tutorial.
Since the ratings are stored as comment meta, you can pull a post’s comments using the REST API as described here https://developer.wordpress.org/rest-api/reference/comments/ and manipulate the data to your achieve your goals.
your tutorial is awesome. I have 2 problem
1- I need star rating display on search page in blog system
2- average rating star above the_content display only 4 star out of 5.
Hello.
Currently the guide does not support displaying the rating outside the single post and extending it to do so is outside the scope of this post I’m afraid.
Regarding your second issue, do you mean you only get 4 empty stars instead of five?
Hi Nik, the card was wonderful, it works perfectly, thank you very much, I felt the need to leave a comment and thank you, good luck.
Hi thanks for this tutorial
i have a problem of not showing stars when a user whants to put a comment and instead show him radio buttons , i’ve added all styles code in style.css but i don’t know why?
please help me thank you.
Hello Dina.
Did you add the styles in the theme’s style.css file or a separate file? If the latter you will need to make sure the file loads properly. You can use your browser’s developer tools to check this. Also if you have any caching systems in place, you should clear all caches and test again.
I have added your code but it is not reflecting on the comment form
It is working properly but just wanted to ask if we can use the all-over rating wherever we want.
The code uses comment-specific hooks, but you could adapt the code for use elsewhere.
Very nice, still usefull after years!
I have one curiosity though… why there’s a zero option in the field?
It’s even hidden by css.
I speak about this line:
0
what’s the purpose?
I believe it’s there to make sure a (zero) value is sent when the user hasn’t selected a rating. It should probably marked as pre-selected though, which seems to be missing from the article. It is used however when checking if required:
if ( ! is_admin() && ( ! isset( $_POST['rating'] ) || 0 === intval( $_POST['rating'] ) ) )
Wow Pretty cool!
Hey I need help with rating plugin that’s not supported anymore. It’d almost perfect but ratings are done outside of the native wordpress commenting system. Do you have any tips on how I can move them into the Native comments in wordpress. Any leads can help. Thanks!
Your best bet would be to look for a plugin which supports migrating your old ratings into the new plugin’s format. If you can’t find one, the only way is to study the old plugin to find out how/where it stores its data, and migrate them manually with PHP. If you are not comfortable with PHP, it would be sensible to hire a developer to do it for you.
HI! Very nice tutorial!
I tried it and unfortunately stars do not show in my frontend.
Some empty circles are shown instead of stars.
No reaction when passing over with mouse…
What can I test to proceed?
Hi Simone,
it could be that you have an error in your code or your file paths, or some styles could be conflicting with your current theme.
I’d first try to switch themes and take it from there. Then you could use your browser’s developer tools to determine if the stylesheet and dashicons are actually loaded. Then, it could be some typo or something.
Welcome to the wonderful world of debugging!
Awesome great solution!