Search

How to Add Star Rating in WordPress Comment (without a Third-Party Plugin)

Star ratings have emerged as a widely adopted and convenient method for gathering user feedback across various online platforms. The simplicity and ease of use associated with star ratings have contributed to their immense popularity on the web. In line with this trend, we can enhance the WordPress commenting feature by introducing our own star rating system.

By incorporating a star rating feature into WordPress comments, website owners can gather valuable insights and opinions from their users in a concise and user-friendly manner. The star rating system provides an intuitive and recognizable method for users to express their satisfaction or dissatisfaction with a particular post, product, or service.

In this tutorial, we’ll show you a method for adding a star rating system for your WordPress commenting feature. This method does not require you to download other third-party plugins, instead, you will make your own plugin for it. Let’s dive in!

Adding Star Rating System to WordPress Comment

Step 1: Create a Folder

To start creating a plugin from your computer, you need to create a folder that will contain all the plugin files we need later. The folder name can be anything, however, to keep it organized the name should be related to the name of your plugin.

Step 2: Create the Main PHP File

Once you’ve created the folder for the plugin, go inside that folder and create a PHP file from your text editor or code editor and give it the same name as the plugin folder.

The PHP file you just created will be the plugin’s main file and will contain all the code required for adding a star rating system for your WordPress commenting feature.

Step 3: Add the Star Rating Custom Codes

The next step is adding custom codes to the PHP file you just created. Copy the following code, paste it into the file, and then save the file.

<?php
/*
Plugin Name: star-rating-comment
Plugin URI: https://www.wppagebuilders.com
Description: Custom Plugin for adding custom code
Version: 1.0.0
Author: WPPagebuilders
Author URI: https://www.wppagebuilders.com/
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/

//Enqueue the plugin's styles.
add_action( 'wp_enqueue_scripts', 'wpp_comment_rating_styles' );
function wpp_comment_rating_styles() {

	wp_register_style( 'wpp-comment-rating-styles', plugins_url( '/', __FILE__ ) . 'assets/style.css' );

	wp_enqueue_style( 'dashicons' );
	wp_enqueue_style( 'wpp-comment-rating-styles' );
}

//Create the rating interface.
add_action( 'comment_form_logged_in_after', 'wpp_comment_rating_rating_field' );
add_action( 'comment_form_after_fields', 'wpp_comment_rating_rating_field' );
function wpp_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', 'wpp_comment_rating_save_comment_rating' );
function wpp_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', 'wpp_comment_rating_require_rating' );
function wpp_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', 'wpp_comment_rating_display_rating');
function wpp_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 the above code accomplish is creating an interface to give a rating while the user types a comment and loads a CSS file to style it, saves the rating along with the comment when submitted, makes the rating required to comment, and displays the rating along with the associated comment in the comment section.

If the star rating system isn’t your requirement to comment on your site, you can delete the following snippets to remove it.

  • Remove the * required symbol from the rating interface by deleting the following snippet from the rating label
<span class="required">*</span>
  • Delete the filter and function that make the rating required
//Make the rating required.
add_filter( 'preprocess_comment', 'wpp_comment_rating_require_rating' );
function wpp_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;
}

Step 4: Adding Stars to the Rating Interface

Once the plugin’s main file is ready, you might want to add some styling to the star rating interface since it’s a bit unattractive and messy like follow.

Let’s replace the rating selection with some stars and line it up nicely. Start by creating a folder and name it “assets” in the same location as your plugin’s main PHP file (the star-rating-comment.php in our case).

Now, open up the newly created assets folder and then create the “style.css” CSS file there. The style.css file will contain all CSS snippets to style the rating interface. The snippets are as follows:

.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;
}

Once you’ve added the CSS snippets to the file, save the file and continue to the next step.

Step 5: Get the Plugin File Ready and Install it

Now all you need to do is to zip the plugin folder to get the plugin ready. You can use any archiver as long as it can archive the file as a ZIP file like follows.

And once you zip it, upload the plugin to your WordPress site. On the Add Plugins page, Click the Upload Plugin button then click the Choose File button or drag the file to the upload box.

Once the file is uploaded, click the Install Now button to install the plugin, and continue by activating the plugin.

By now, your commenting feature will have the star rating system incorporated into it. You can see the result by leaving a comment.

And see your star-rated comment in the comment section.

Additional Options

Display the Average Rating of Posts

For an additional option to extend the plugin feature, this step will guide you to display the average ratings of your posts by adding more custom codes to the plugin’s main PHP file. The average rating will be displayed on your single post and on each post in your main blog post (the star displays depend on your theme) just before the content.

Add the following custom codes at the bottom of your plugin’s main PHP file (star-rating-comment.php in this case).

//Get the average rating of a post.
function wpp_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', 'wpp_comment_rating_display_average_rating' );
function wpp_comment_rating_display_average_rating( $content ) {

	global $post;

	if ( false === wpp_comment_rating_get_average_ratings( $post->ID ) ) {
		return $content;
	}
	
	$stars   = '';
	$average = wpp_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">Post\'s average rating is: ' . $average .' ' . $stars .'</p>';
	$custom_content .= $content;
	return $custom_content;
}

Below is the screenshot for the post average rating in a single post.

The Bottom Line

Incorporating a star rating system into WordPress comments offers a simple and efficient way to gather user feedback. This approach enhances user engagement, encourages meaningful interactions, and provides valuable insights to website owners. By implementing this feature, website owners can leverage user ratings to improve their service and the overall user experience on their WordPress-powered websites.

This page may contain affiliate links, which help support our project. Read our affiliate disclosure.
Hendri Risman

Hendri Risman

Hendri is a WordPress expert and a writer staff at WPPagebuilders. He writes solutions on how to get things fixed in WordPress a lot. Mostly without involving a plugin.
Want to save yearly expense up to $219? why not?

Leave a Comment