Skip to content

Instantly share code, notes, and snippets.

@ChromeOrange
Created July 29, 2012 20:48
Show Gist options
  • Save ChromeOrange/3201772 to your computer and use it in GitHub Desktop.
Save ChromeOrange/3201772 to your computer and use it in GitHub Desktop.
Add star ratings to the Product category page and by the product name on the single product page
<?php
add_action( 'woocommerce_after_shop_loop_item','show_rating_stars' );
add_action( 'woocommerce_single_product_summary','show_rating_stars',15 );
function show_rating_stars() {
global $woocommerce,$post, $wpdb;
if ( comments_open() ) :
$count = $wpdb->get_var("
SELECT COUNT(meta_value) FROM $wpdb->commentmeta
LEFT JOIN $wpdb->comments ON $wpdb->commentmeta.comment_id = $wpdb->comments.comment_ID
WHERE meta_key = 'rating'
AND comment_post_ID = $post->ID
AND comment_approved = '1'
AND meta_value > 0
");
$rating = $wpdb->get_var("
SELECT SUM(meta_value) FROM $wpdb->commentmeta
LEFT JOIN $wpdb->comments ON $wpdb->commentmeta.comment_id = $wpdb->comments.comment_ID
WHERE meta_key = 'rating'
AND comment_post_ID = $post->ID
AND comment_approved = '1'
");
if ( $count > 0 ) :
$average = number_format($rating / $count, 2);
echo '<div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating"';
if ( is_product() ) :
echo ' class="single_product_rating"';
else :
echo ' class="loop_rating"';
endif;
echo '>';
echo '<div class="star-rating" title="'.sprintf(__('Rated %s out of 5', 'woocommerce'), $average).'"><span style="width:'.($average*16).'px"><span itemprop="ratingValue" class="rating">'.$average.'</span> '.__('out of 5', 'woocommerce').'</span></div>';
echo '</div>';
if ( is_product() ) :
echo '<div class="clear"></div>';
else :
echo '';
endif;
endif;
endif;
}
?>
@nehagosavi
Copy link

Hello,
I tried this in my functions.php but it is not working.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment