Star ratings for WordPress
There are a lot of plugins and various methods for attaching star ratings to WordPress posts – but this is by far the simplest and is great for sites where you review anything, be it music, films, products etc. The first thing you need to do, is setup a custom field for your stars. You don’t need to do anything with code for this, simply go into a post and where the custom fields section is, add a new one giving it the name “starrating”. If there’s no custom fields section, go to screen options and make sure it’s visible.
Then, give your post a star rating in the value field. For the sake of this article, the star ratings are 1,2,3,4,5. But you could have it up to 10, and if you want half-star ratings you could have 1.5,2.5 etc. Save your post.
Now we’re going to use the WordPress get_post_meta function to display our stars. The default code for this will simply display the value you entered as text. Of course, we don’t want it to just show up as “4”, we want an image of 4 stars. So the trick is to wrap the code inside an img tag. This then causes the value you entered in the custom field to form part of the img src URL. For example, if you entered a value of 1, the img src would become /images/star1.jpg. A value of 2 would become /images/star2.jpg – and so on. We are essentially using the value of our custom field to alter the img src.
All you then need to do is create your star images, saving each one with a filename that reflects the rating it’s for. So your 1 star rating image should be called star1.jpg, and so on.
It’s worth baring in mind if you enter a value into the field that doesn’t exist as an image, then nothing will show up. So if for example, you want to be able to use half-star ratings, you need to create additional images, saving them as “star15″, “star25″ etc. You can’t save your images as “star1.5.jpg” which is why it shows up as 15, so when you enter the value in the custom field you need to enter 15, 25, 35 for a 1.5 star rating, 2.5 star rating, 3.5 star rating etc.
You should also wrap your code in conditionals, so the website only attempts to display a star rating for posts that are in a particular category, e.g. reviews. You should also save a blank image called star.jpg so that if you don’t attach a star rating to a review, it doesn’t throw up a missing image error. There’s probably some sort of conditional code for WordPress that could handle this but it’s the easiest way.
You can see a working example here.