使用评论时WP_Comment_Query
, 。因此,您需要使用专用的wordpressWPDB
类来使用简单的轻量级SQL查询。
在下面的代码中,您可以更改样式和html结构以获得所需的输出。您还可以使用可用的短码参数 ” _(默认设置为 )设置_要以随机顺序显示的评论数:
add_shortcode('woo_reviews', 'get_random_woo_reviews');
function get_random_woo_reviews( $atts ){
// Shortcode Attributes
$atts = shortcode_atts( array(
'limit' => '5', // <== Set to 5 reviews by default
), $atts, 'woo_reviews' );
global $wpdb;
// The sql random query on product reviews
$comments = $wpdb->get_results( $wpdb->prepare("
SELECT *
FROM {$wpdb->prefix}comments c
INNER JOIN {$wpdb->prefix}posts p ON c.comment_post_ID = p.ID
WHERE c.comment_type = 'review' AND p.post_status = 'publish'
ORDER BY RAND() LIMIT %d
", intval( esc_attr($atts['limit']) ) ) );
ob_start(); // Start buffering
## CSS applied styles
?>
<style>
ul.product-reviews, ul.product-reviews li { list-style: none; margin:0; padding:0; line-height: normal;}
ul.product-reviews li { display:block; max-width: 200px, padding: 10px; display:inline-block; vertical-align: text-top;}
ul.product-reviews li .title {font-size: 1.2em;}
ul.product-reviews li .content {max-width: 180px; font-size: 0.9em; margin-bottom: 6px;}
ul.product-reviews li .author, ul.product-reviews li .date {display: block; font-size: 0.75em;}
</style>
<?PHP
## HTML structure
?>
<ul class="product-reviews"><?PHP
foreach ( $comments as $comment ) {
?>
<li>
<h4 class="title"><?PHP echo get_the_title( $comment->comment_post_ID ); ?></h4>
<div class="content"><?PHP echo $comment->comment_content; ?></div>
<span class="author"><?PHP printf( __("Posted By %s") . ' ', '<strong>' . $comment->comment_author . '</strong>' ); ?></span>
<span class="date"><?PHP printf( __("On %s"), '<strong>' . date_i18n( 'l jS \of F Y', strtotime( $comment->comment_date) ) . '</strong>' ); ?></span>
</li>
<?PHP
}
?></ul><?PHP
return ob_get_clean(); // Return the buffered output
}
代码进入您的活动子主题(或活动主题)的function.PHP文件中。经过测试和工作。
[woo_reviews]
或在PHP中:echo do_shortcode( "[woo_reviews]" );