WooCommerce: Display some 5 stars rating products reviews randomly

Viewed 983

Based on WooCommerce: Display some reviews randomly on home page answer code, I am using the following code that shows 5 random reviews:

function get_woo_reviews()
{
    $comments = get_comments(
        array(
            'status'      => 'approve',
            'post_status' => 'publish',
            'post_type'   => 'product',
        )
    ); 
    shuffle($comments);
    $comments = array_slice( $comments, 0, 5 );
    $html = '<ul>';
    foreach( $comments as $comment ) :
        $rating = intval( get_comment_meta( $comment->comment_ID, 'rating', true ) );
        $html .= '<li class="review">';
        $html .= '<div>'.get_the_title( $comment->comment_post_ID ).'</div>';
        if ( $rating > 4 ) $html .= wc_get_rating_html( $rating );
        $html .= '<div>' .$comment->comment_content.'</div>';
        $html .= "<div>Posted By :".$comment->comment_author." On ".$comment->comment_date. "</div>";
        $html .= '</li>';
    endforeach;
    $html .= '</ul>';
    ob_start();
    echo $html;
        $html = ob_get_contents();
    ob_end_clean();

    return $html;
}
add_shortcode('woo_reviews', 'get_woo_reviews');

But It also shows some comments without any rating.

How to change this code to show only 5 star rating reviews?

1 Answers

A "meta query" is required to the WP_Comment_Query based on "rating" meta key set to 5 stars meta value, to get random reviews that have 5 stars rating, as follows:

function get_random_five_stars_products_reviews( $atts ) {
    // Extract shortcode attributes
    extract( shortcode_atts( array(
        'limit' => 5, // number of reviews to be displayed by default
    ), $atts, 'woo_reviews' ) );

    $comments = get_comments( array(
        'status'      => 'approve',
        'post_status' => 'publish',
        'post_type'   => 'product',
        'meta_query'  => array( array(
            'key'     => 'rating',
            'value'   => '5',
        ) ),
    ) );

    shuffle($comments);

    $comments = array_slice( $comments, 0, $limit );

    $html = '<ul class="products-reviews">';
    foreach( $comments as $comment ) {
        $rating = intval( get_comment_meta( $comment->comment_ID, 'rating', true ) );
        $html .= '<li class="review">';
        $html .= '<div>'.get_the_title( $comment->comment_post_ID ).'</div>';
        if ( $rating > 4 ) $html .= wc_get_rating_html( $rating );
        $html .= '<div>' .$comment->comment_content.'</div>';
        $html .= "<div>Posted By :".$comment->comment_author." On ".$comment->comment_date. "</div>";
        $html .= '</li>';
    }
    return $html . '</ul>';
}
add_shortcode('woo_reviews', 'get_random_five_stars_products_reviews');

Code goes in functions.php file of the active child theme (or active theme). Tested and works

USAGE: [woo_reviews] or [woo_reviews limit="3"] for 3 random reviews for example.

Related