Get rating product by product id
How to get product rating by product_id without loop?
I have one product_id and i want get product rating, how can I do this and it is feasible? Thank
How to get product rating by product_id without loop?
I have one product_id and i want get product rating, how can I do this and it is feasible? Thank
Given a product ID you can get the average rating like this:
$product = wc_get_product( $product_id );
$rating = $product->get_average_rating();
That'll return the raw number (4.00, 3.50 etc.).
To output the rating HTML for a given product you can use this code:
$product = wc_get_product( $product_id );
$rating = $product->get_average_rating();
$count = $product->get_rating_count();
echo wc_get_rating_html( $rating, $count );
Or, if you're in the loop you can use this function to get the HTML for the current product:
woocommerce_template_loop_rating()
You can fetch loop top rating product
$args_top_rating1 = array(
'post_type' => 'product',
'meta_key' => '_wc_average_rating',
'orderby' => 'meta_value',
'posts_per_page' => 8,
'status'=>'publish',
'catalog_visibility'=>'visible',
'stock_status'=>'instock'
);
$top_rating = new WP_Query( $args_top_rating1 );
while ( $top_rating->have_posts() ) : $top_rating->the_post(); global $product;
$urltop_rating = get_permalink($top_rating->post->ID) ;
$rating_count = $product->get_rating_count();
$average_rating = $product->get_average_rating();
echo wc_get_rating_html( $average_rating, $rating_count);
endwhile;
This helped me a lot, create the get_star_rating () function and return your html.
NOTE: If it is in a loop
function get_star_rating() {
global $woocommerce, $product;
$average = $product->get_average_rating();
$review_count = $product->get_review_count();
return '<div class="star-rating">
<span style="width:'.( ( $average / 5 ) * 100 ) . '%" title="'.
$average.'">
<strong itemprop="ratingValue" class="rating">'.$average.'</strong> '.__( 'out of 5', 'woocommerce' ).
'</span>
</div>'.'
<a href="#reviews" class="woocommerce-review-link" rel="nofollow">( ' . $review_count .' )</a>';
}
Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.