Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get WooCommerce Star Ratings in Loop

I have a custom template I built for my WooCommerce Shop Page that pulls in products by categories for different sections.

I need to know how I can pull the star ratings into the loop for each product. All the searching I've done for hours results in nothing.

like image 406
minemindmedia Avatar asked Nov 30 '25 02:11

minemindmedia


2 Answers

I was able to answer my own question. Here's how to get the star ratings in the loop.

Start by using the following 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; ?>

Make sure to include the css class: woocommerce to the container, for example:

<ul class="woocommerce">
<li>
    <?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; ?>
</li>
</ul>

Furthermore, I ended changing the sizes and colors of the stars:

    .woocommerce {
        .star-rating {
      width: 110px !important;
      height: 30px !important;
      float: left;
      &:before {
        font-size: 20px;
      }
      span {
        &:before {
          font-size: 20px;
          color: #ffa500;
        }
      }
    }
like image 193
minemindmedia Avatar answered Dec 01 '25 16:12

minemindmedia


Do you mean something like this?

global $product;
echo $product->get_rating_html();
like image 20
Twnzl Avatar answered Dec 01 '25 17:12

Twnzl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!