WooCommerce随机展示一些五星评级的产品评论

WooCommerce随机展示一些五星评级的产品评论

基于WooCommerce:在主页上随机显示一些评论

基于WooCommerce:在主页上随机显示一些评论答案代码,我使用以下代码显示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 = ‘

    ‘;
    foreach( $comments as $comment ) :
    $rating = intval( get_comment_meta( $comment->comment_ID, ‘rating’, true ) );
    $html .= ‘

  • ‘;
    $html .= ‘

    ‘.get_the_title( $comment->comment_post_ID ).’

    ‘;
    if ( $rating > 4 ) $html .= wc_get_rating_html( $rating );
    $html .= ‘

    ‘ .$comment->comment_content.’

    ‘;
    $html .= “

    Posted By :”.$comment->comment_author.” On “.$comment->comment_date. “

    “;
    $html .= ‘

  • ‘;
    endforeach;
    $html .= ‘

‘;
ob_start();
echo $html;
$html = ob_get_contents();
ob_end_clean();

return $html;
}
add_shortcode(‘woo_reviews’, ‘get_woo_reviews’);

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

如何将此代码更改为仅显示5星级评价?

WooCommerce随机展示一些五星评级的产品评论

需要对WP_Comment_Query基于“rating”的meta键进行“meta query”,将meta键设置为5星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 = ‘

    ‘;
    foreach( $comments as $comment ) {
    $rating = intval( get_comment_meta( $comment->comment_ID, ‘rating’, true ) );
    $html .= ‘

  • ‘;
    $html .= ‘

    ‘.get_the_title( $comment->comment_post_ID ).’

    ‘;
    if ( $rating > 4 ) $html .= wc_get_rating_html( $rating );
    $html .= ‘

    ‘ .$comment->comment_content.’

    ‘;
    $html .= “

    Posted By :”.$comment->comment_author.” On “.$comment->comment_date. “

    “;
    $html .= ‘

  • ‘;
    }
    return $html . ‘

‘;
}
add_shortcode(‘woo_reviews’, ‘get_random_five_stars_products_reviews’);

代码放在活动子主题(或活动主题)的functions.php文件中。测试和工作

随机展示一些五星评级的产品评论用法:

用法:[woo_reviews]或[woo_reviews limit=”3″]以3篇随机评论为例。

类似文章