如何解决随机显示一些内容长度有限的 WooCommerce 产品评论
我正在为基于 WooCommerce: Display some reviews randomly on home page 的评论制作简码,以便放在其他页面上。如何按字符数限制评论,例如 100 或 200 个字符。所以它们不会太长并且适合任何页面。
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,$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');
解决方法
要限制显示 5 个开头的评论,内容不超过特定长度(此处为 100 个字符),请使用以下内容:
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
'length' => 100,// Limit comments text content lenght
'show_stars' => true,// Or "false" to hide
),$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);
$count = 0; // Initializing
$html = '<ul class="products-reviews">';
foreach( $comments as $comment ) {
$content = $comment->comment_content;
if( strlen($content) <= $length && $count < $limit ) {
$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 ( $show_stars ) {
$html .= wc_get_rating_html( $rating );
}
$html .= '<div>' .$content. '</div>';
$html .= "<div>Posted By :".$comment->comment_author." On ".$comment->comment_date. "</div>";
$html .= '</li>';
$count++; // Increase count
}
if ( $count == $limit ) {
break; // Stop the loop
}
}
return $html . '</ul>';
}
add_shortcode('woo_reviews','get_random_five_stars_products_reviews');
代码位于活动子主题(或活动主题)的functions.php 文件中。它应该有效。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。