Get WooCommerce Star Ratings in Loop

18,890

Solution 1

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;
        }
      }
    }

Solution 2

Do you mean something like this?

global $product;
echo $product->get_rating_html();
Share:
18,890
minemind
Author by

minemind

Updated on June 05, 2022

Comments

  • minemind
    minemind almost 2 years

    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.

  • Ajay Ghaghretiya
    Ajay Ghaghretiya over 6 years
    how to get the average rating without the global variable $product. I have product id.
  • rCgLT
    rCgLT over 2 years
    get_rating_html() is depracated