WP Post Ratings plugin: Show star images only

2011/10/08

There are many star rating plugins for WordPress available, while the plugin “GD Star Rating” has many functions, is the “WP Post Ratings” plugin much easier to use. There is one feature I like to see in the last mentioned plugin: A static result view!

People should rate your content on the page where the article or product is located and not on other pages, but showing a rating on other place can increase your CTR.
The following function will show only the images for a given post ID. Install WP Post Ratings (if you don’t have already), add this function into your functions.php file and place the function name into your WordPress theme file.

function showRating($id, $css_class = 'post-ratings') {
	global $wpdb;
	$path = plugins_url('wp-postratings/images/'.get_option('postratings_image'));
	$rating = $wpdb->get_var("SELECT AVG(rating_rating) AS rating FROM $wpdb->ratings WHERE rating_postid = $id");
	$i = 0;
	$html = '
		<span class="'.$css_class.'">';
	if (!empty($rating)) {
		while ($i < floor($rating)) {
			$html .= '
			<img src="'.$path.'/rating_on.gif" alt="" />';
			$i++;
		}
		if (round($rating, 1) == ($i+0.5)) {
			$html .= '
			<img src="'.$path.'/rating_half.gif" alt="" />';
			$i++;
		}
	}
	while ($i < 5) {
		$html .= '
		<img src="'.$path.'/rating_off.gif" alt="" />';
		$i++;
	}
	$html .= '
		</span>';
	return $html;			
}

That’s all, I hope the WordPress plugin author will add this functionality very soon.

4 comments to “WP Post Ratings plugin: Show star images only”

  1. Carlos says:

    Hi,

    I incorporated this function but not sure how to invoke it? I placed it in a php template but nothing is appearing. Can you provide an example? Thanks!

  2. Olaf says:

    Hello Carlos.

    do you installed the WP Post Ratings plugin?
    The code inside the theme must be (inside the loop)

    echo showRating(get_the_ID(), 'some_style_class');

    Place the code inside the single.php theme and it should work.

  3. Jordash says:

    Awesome script, do you have any idea how to output variables like number of votes?

    Thanks for the share!

  4. Olaf says:

    Hi Jordash,

    this kind of query should do the trick:

    $num_ratings = $wpdb->get_var("SELECT COUNT(*) AS num_ratings FROM $wpdb->ratings WHERE rating_postid = $id");

    I haven’t tried the code, because I don’t use the plugin at the moment.