How do you add the star ratings for products in woocommerce? How do you add the star ratings for products in woocommerce? wordpress wordpress

How do you add the star ratings for products in woocommerce?


There's actually a much more terse way to handle this. Just use the built-in functions that Woocommerce has built out:

add_action('woocommerce_after_shop_loop_item', 'get_star_rating' );function get_star_rating(){    global $woocommerce, $product;    $average = $product->get_average_rating();    echo '<div class="star-rating"><span style="width:'.( ( $average / 5 ) * 100 ) . '%"><strong itemprop="ratingValue" class="rating">'.$average.'</strong> '.__( 'out of 5', 'woocommerce' ).'</span></div>';}

I've confirmed that this works for me.


You can put this into your themes functions.php file:

add_action('woocommerce_after_shop_loop_item', 'my_print_stars' );function my_print_stars(){    global $wpdb;    global $post;    $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 class="starwrapper" itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">';    echo '<span 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> </span></span>';    echo '</div>';    }}

Note that you may need to change woocommerce_after_shop_loop_item to a different hook depending on your design and where exactly you want the stars to show up.

This page lists WooCommerce action hooks: http://wcdocs.woothemes.com/codex/extending/hooks/ . I don't see any hooks associated with the thumbnail specifically, but you may try woocommerce_after_shop_loop_item_title or woocommerce_after_shop_loop_item.

(This function is essentially copied from WooCommerce's single-product-reviews.php)


As of WooCommerce 3.0+ this is the correct code:

$product = wc_get_product( $id );echo wc_get_rating_html( $product->get_average_rating() );

The get_rating_html() method on the product object has been deprecated.

More information here: https://docs.woocommerce.com/wc-apidocs/function-wc_get_rating_html.html