WooCommerce:随机显示一些 5 星评级的产品评论

WooCommerce: Display some 5 stars rating products reviews randomly

基于 答案代码,我使用以下显示 5 条随机评论的代码:

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');

但它也显示了一些没有任何评级的评论。

如何更改此代码以仅显示 5 星级评论?

根据 “评级” 元键设置为 5 星WP_Comment_Query 需要“元查询” meta值,获取5星评价的随机评论,如下:

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');

代码进入活动子主题(或活动主题)的 functions.php 文件。已测试并有效

用法[woo_reviews][woo_reviews limit="3"] 例如 3 条随机评论。