Adding a Star Rating System to WordPress

in WordPress Tutorials

This is an advance WordPress tutorial on how to add an star rating system to your WordPress blog. The star rating system can be used to rate articles posts or content of any type for that matter. I will demonstrate how you can add a five star rating system to your blog without the use of a plug-in. It will involve some custom code, but I will give you all the snippets for you to install in your current theme. If you follow the process in this tutorial, you can end up with a five star rating system that looks something like the one at the bottom of the following screen-shot:

wordpress ratings


If you are going to attempt this tutorial, you should have a decent knowledge of PHP, JavaScript, HTML and WordPress. You don’t need to be an expert in each, but a little background information will help. I will walk you through the process step by step and make it as easy as possible for you to add my star rating system to your WordPress blog.

Making Star Images

First thing you can do is make two stars, one colorful star for the selected state and one dull one for the unselected state. I found that gray and yellow work nice. Feel free to use my stars below or make your own with Inkscape’s star tool. If you don’t have Inkscape, Google it and download it. It is free! You should probably make sure you have a transparent background in case you have a background color for your WordPress site. To save Inkscape drawings with a transparent background, you have to export it as a bitmap. Here is what my finished stars were like:



The first gray star is for nonactive and the yellow star is for active stars. For example, if you had three stars selected, the app would show three yellow stars followed by two gray stars indicating three was chosen by the user.

Prepare WordPress for Star Rating System

There are a few preparations you have to make in order for the star rating system we are building to work. Please follow the instructions here before continuing so everything will work smoothly:

  1. Go to the database your installation of WordPress is using and add a table to it named “ratings”. This way, you don’t clutter up the default post table and can clean this ratings table up anytime you wish without harming any default WordPress behaviors. Add two fields to your empty table and name them postID and rating so WordPress can keep track of what posts received ratings.
  2. Open your WordPress site in your favorite FTP program and navigate to your blog’s main folder. This will be the same folder that contains the folders named wp-admin, wp-content and wp-includes. Add a new folder here named “IansPics”. This will be the folder where you can place any images for your star rating system. Go ahead and upload your two star images to this folder now. Unless you add any other images later, this is all you need in this folder.

Adding the Star Rating Code

Next we have to add some code to the loop in your current theme to make the star ratings work. In most themes, the loop can be found in the index.php file. I want to point out that some themes such as the Eclipse theme may have the WordPress loop in a different file. If you are using the Eclipse theme, the loop for posts is in the file named post-actions.php in the …eclipse/core/actions directory.

Once you have found the file containing the WordPress loop for your site’s posts, you will add the following code wherever, in the loop, you want the five star rating widget to appear. I choose to place mine at the bottom of each post. Use the following Iframe to call your widget which we will build next:

<!--######################## star ratings iFrame widget #######################--> 
<iframe src="//localhost/wordpress/?page_id=35&pi=<?php echo $theidof; ?>" width="433px" height="130px" border="1"></iframe>

Now we need to build two scripts for the above inline frame. The first script is going to be the form that contains that stars users will click on to select a rating from one to five. The second script is the one that the first script submits data to so it can update the rating info in the database for the post or article being rated. Both will be made into template files so that they will integrate into WordPress seamlessly.

Adding Template Tag to star_frame.php Template

The first file you need to create we will call star_frame.php. First give it a template name so we can access it from the WordPress admin. Add the following template tag to your currently empty PHP file named star_frame.php. Also add the $urated variable that returns the user ratings from the other script we will be making later.

/* Template Name: starRatingFrame */ 
$urated = $_GET['x'];

The above code is the start to your first template file, star_frame.php.

Adding JavaScript to star_frame.php Template
Next, we add the following JavaScript code to the same file:

//star ratings script to rate items from 1-5 stars.
//written by: Ian L. of
var picnm = "IansPics/star2.png";  // good star.
var picnm2 = "IansPics/star.png";  // bad star.
//@@@@@@@@@@@@@@@@@@@@  1:  @@@@@@@@@@@@@@@@@@@@@@
function star(num,n,x) {
   var star1a = document.getElementById(n+'1');
if(num > 1){
   var star2a = document.getElementById(n+'2');
   var star2a = document.getElementById(n+'2');
if(num > 2){
   var star3a = document.getElementById(n+'3');
   var star3a = document.getElementById(n+'3');
if(num > 3){
   var star4a = document.getElementById(n+'4');
   var star4a = document.getElementById(n+'4');
if(num > 4){
   var star5a = document.getElementById(n+'5');
   var star5a = document.getElementById(n+'5');
//change span & hidden input values:
//submit the form to php script that records rating in db only if nosubmit param not used:
}//end star function.

The code above is most of the JavaScript for the star rating system and consists mostly of the function named star which I developed specifically for the star rating system.

Adding PHP to star_frame.php Template

After the JavaScript you still need to add the following PHP code to star_frame.php:

//get ratings from database for the_ID();
global $wpdb;
$theid = $_GET['pi'];
$restars = mysql_query("SELECT rating FROM ratings WHERE postID='$theid'") or die(mysql_error());
$cntstar = 0;
$allrate = 0; nosubmit"){docu
	while($rrr=mysql_fetch_array($restars)) {
	$crate = $rrr['rating'];
	$allrate = $allrate+$crate;
	}//end while.
if($cntstar > 0){
$avgrate = round($allrate/$cntstar,2);
$avgrate = 0;
<div id="ratings">
<form name="cform" id="cform" method="post" action="">
<br />
<table cellspacing="2">
<td valign="top"><span  style='color:#CCCCCC;font-size:18px;'>
Rate This Article:
<td colspan="3" valign="top">
<span style="position:relative;top:-7px;color:#CCCCCC;font-size:12px;vertical-align:text-top;">Your Rating: <span id='looksur'></span><br />average rating:  <span id="looks"><?php echo $avgrate; ?></span> out of 5 stars | voted on <?php echo $cntstar; ?> times.</span>
<input type="hidden" id="looksof" name="looksof" value=3 />
<input type="hidden" id="cURL" name="cURL" value="<?php echo $curURL; ?>" />
<input type="hidden" id="pid" name="pid" value="<?php echo $theid; ?>" />
<script type="text/javascript">
//set beginning star values:
//document.getElementById('looks').innerHTML='<?php echo $avgrate; ?>';
//this PHP is within JavaScript so be careful here!!!
echo "<script>star($urated, 'looks', 'nosubmit');</script>";
}//end if user entered a rating, set stars accordingly.

Once you have included the template tag, JavaScript and PHP code snippets above into your star_frame.php file, save it and upload it to your theme’s main folder. If you were using the Eclipse them, you would upload it to wp-content/themes/eclipse or if you are using twentyeleven, upload it to wp-content/themes/twentyeleven.

Building the star_rating.php Template
Once you have uploaded the previous template, you have to build just one more template file to process the form from the previous template. We are going to name this second template file star_rating.php. I don’t recommend changing the names of either of these templates because the names are used within the code and you may forget to change something if you don’t use the same names. First step to building the star_rating.php template file is to add the template tag at the start of the empty PHP file as we did before with star_frame.php. The main purpose of the star_rating.php template file is to store your users ratings into the database table we made earlier named ratings. This is going to be a relatively simple file, so here is the whole thing at once this time:

/* Template Name: starRating */
$rating = $_POST['looksof'];
$curURL = $_POST['cURL'];//This is the URL of this script(iframe), not what is in address bar of browswer!
$PID = $_POST['pid'];
$starz = "";
if($rating > 1){$starz="s";}
echo "<br /><span style='color:#CCCCCC'>Submitting your rating of $rating star$starz. Thank you!</span>";
//insert rating into db:
global $wpdb;
	INSERT INTO ratings (postID,rating) VALUES($PID,$rating)
echo "<script>setTimeout(\"window.location.href='$curURL&x=$rating'\",3333);</script>";

If you noticed while creating the first template file above, the one called star_frame.php, you would have seen that star_rating.php is called from the action attribute of the form. Since star_frame.php is called from the posts page, it hooks into the loop and passes the post ID and rating to star_rating.php which then puts the information into the ratings table we created earlier.

Finishing Up

Now you should have all the components for your star rating system. Upload the two template files you created to your theme directory and follow these easy steps to activate them:

  1. Go to the WordPress admin page for your site and click add new page.
  2. Give the page a similar title to the template file such as Star Frame.
  3. In the right column of the default admin page, under template, select the starRatingFrame template and click on Update to save the page.
  4. View the page you just created by clicking on the view page link at the top of the admin area.
  5. Copy the URL of the new page from the address bar of your browser and paste it into the file in which you inserted the iframe for your start rating system, the file that contains the WordPress loop for posts. You should be pasting it in place of the src URL for the iframe tag in index.php or possibly post-action.php if you are using the Eclipse theme.
  6. Repeat steps one through four for your second template file, starRating.
  7. This time copy the URL for the new page you created and paste it into the form’s action attribute in star_frame.php(in red text above).


That should do it. If you did all of the steps correctly in this tutorial, your star rating system should be working now. Test it by rating a couple articles and if it’s not working, go back and find where you made an error. The system will keep track of everyone’s ratings and give the average rating each post or article has received over time. You should notice the average change each time you rate a post or article. You can dress your star rating system up by adding fancier stars or adding some HTML and CSS as you see fit to make it your own. This is a basic bare-bones version just to get you up and running. Good luck with your rating system and have fun making it!

Comments (7)

  • Comment by Ahmad Fahrurroji
    Ahmad Fahrurroji

    I have tried but still showing an error “No database selected”. How to solve it?

  • Comment by sandy

    star is not showing up on my localhost. I think src of star is not working. How could I change the src of star at my localhost

  • Comment by Ian Lin
    Ian Lin

    Yes, good catch. Sorry about that. I am not sure how that got into the tutorial’s code snippet, but you can simply omit [nosubmit”){docu” ] from that line of code and it should work. that was not supposed to be there at all. Let me know if you need more help or if that doesn’t work, but it should. -Ian L.

  • Comment by Daryl

    Im getting an error on line 64 of star_frame

    here:$allrate = 0; nosubmit”){docu
    while($rrr=mysql_fetch_array($restars)) {
    $crate = $rrr[‘rating’];
    $allrate = $allrate+$crate;
    }//end while.
    if($cntstar > 0){
    $avgrate = round($allrate/$cntstar,2);
    $avgrate = 0;

    * the double quote after no submit (nosubmit”) is throwing the error

  • Comment by free shoutbox for blog
    free shoutbox for blog

    Excellent tutorial. I love this, was searching in Google for this one and this is what I was wondering for.
    Thanks for this great post.

  • Comment by Dietmar

    Wouldn’t it be better to use the post meta table for storing the information about the rating? I mean, you can get the stored value of the post_meta (Let’s call it _my_rating), than add the clicked amount of stars and divide it with the total number os ratings. After that store the new value in the post_meta table. So you prevent to add new tables to your wordpress database which I think is not a good idea.
    Also adding some AJAX magic would spice it up again!

  • Comment by Shuvo Habib
    Shuvo Habib

    Great Article…. I’m going to integrate it on my website now…!!