John Davidson

php - WooCommerce: Get reviews from products in array and sort them by stars

0 comments
Message:


I want to show some reviews based on a list of products.
The product IDs are stored in an array. So I tried the following:


<?php
$args = array (
'post_type' => 'product',
'number' => '5',
'post_id' => array('2360','2362'),
);
$comments = get_comments( $args );
wp_list_comments( array( 'callback' => 'woocommerce_comments' ), $comments);
?>

It looks, that post_id does not allow an array of IDs.
If I try it with only one ID it works fine.


EDIT: I found a way to order by star rating:


'meta_key' => 'rating',
'orderby' => 'meta_value_num',
'order' => 'DESC'


My Answer:
php
$product_ids = array(1, 2, 3);

$args = array(
'post_type' => 'product',
'post__in' => $product_ids,
);

$products = get_posts($args);

foreach ($products as $product) {
$product_reviews = get_comments(array(
'post_id' => $product->ID,
'status' => 'approve',
));

usort($product_reviews, function($a, $b) {
$stars_a = get_comment_meta($a->comment_ID, 'rating', true);
$stars_b = get_comment_meta($b->comment_ID, 'rating', true);

return $stars_b - $stars_a;
});

foreach ($product_reviews as $review) {
echo 'Product: ' . get_the_title($product->ID) . '
';
echo 'Rating: ' . get_comment_meta($review->comment_ID, 'rating', true) . ' stars
';
echo 'Review: ' . $review->comment_content . '

';
}
}


This code will retrieve reviews for each product in the array, sort them by the number of stars, and then display the product title, rating, and review content for each review.

Rate this post

3 of 5 based on 7285 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us