I am using a function based on this answer to add the star rating to the product loop (unless it's the front page):
add_action('woocommerce_shop_loop_item_title', 'add_star_rating' );
function add_star_rating()
{
if(!is_front_page()){
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>';
}
}
If there are no reviews yet the page shows the 5 grey stars. How can I change it so that if there are no reviews for the product yet then it shows the text 'Be the first to review' or similar static text.
I can then also use this to add the 'Be the first to review' on the product page well, where no star rating is shown if there are no reviews. I can't find a way to count the reviews and check if zero.
I've also tried this but it doesn't seem to make a difference:
add_action('woocommerce_shop_loop_item_title', 'add_star_rating' );
function add_star_rating()
{
if(!is_front_page()){
global $woocommerce, $product;
$average = $product->get_average_rating();
$count = $product->get_rating_counts();
if ($count > 0){
echo '<div class="star-rating"><span style="width:'.( ( $average / 5 ) * 100 ) . '%"><strong itemprop="ratingValue" class="rating">'.$average.'</strong> '.__( 'out of 5', 'woocommerce' ).'</span></div>';
}
else {
echo '<div>No reviews yet</div>';
}
}
}
get_average_rating
probably just gets you an “average” of0
for these products, I suppose. Useget_rating_counts
to check if there actually where any reviews for the product, and then base your output on that. – CBroeWC_Product
class has this property defined as an array,'rating_counts' => array(),
- so check what gets actually returned by this method, it does not appear to be a mere number. – CBroe