Issue
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>';
}
}
}
Solution
This should suffice as an extra check
function add_star_rating() {
// Check if reviews ratings are enabled - WooCommerce Settings
if ( ! wc_review_ratings_enabled() ) {
return;
}
if( !is_front_page() ) {
global $product;
// Get average
$average = $product->get_average_rating();
// Average > 0
if ($average > 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>';
}
}
}
add_action('woocommerce_shop_loop_item_title', 'add_star_rating', 10 );
Answered By - 7uc1f3r Answer Checked By - Gilberto Lyons (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.