WooCommerce Show Star Ratings on a Loop

If you are using a custom theme template and want to show the product star ratings on a loop in a query, you may use this code.

<?php if ($average = $product->get_average_rating()) : ?>
<?php echo '<div class="star-rating" title="'.sprintf(__( 'Rated %s out of 5', 'woocommerce' ), average).'"><span style="width:'.( ( $average / 5 ) * 100 ) . '%"><strong itemprop="ratingValue" class="rating">'.$average.'</strong> '.__( 'out of 5', 'woocommerce' ).'</span></div>'; ?>
<?php endif; ?>

Sample Result:

If you want to show the stars even though the product has 0 ratings, try removing the if statement, so the code will be like this

<?php $average = $product->get_average_rating(); ?>
<?php echo '<div class="star-rating" title="'.sprintf(__( 'Rated %s out of 5', 'woocommerce' ), average).'"><span style="width:'.( ( $average / 5 ) * 100 ) . '%"><strong itemprop="ratingValue" class="rating">'.$average.'</strong> '.__( 'out of 5', 'woocommerce' ).'</span></div>'; ?>

Sample Result: