I want to have 5 random reviews appear on my home page each time someone visits.
I found some code to fetch all the reviews:
//add get product reviews to homepage
function get_woo_reviews()
{
$count = 0;
$html_r = "";
$title="";
$args = array(
'post_type' => 'product'
);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
foreach($comments as $comment) :
$title = ''.get_the_title( $comment->comment_post_ID ).'';
$html_r = $html_r. "" .$title."";
$html_r = $html_r. "" .$comment->comment_content."";
$html_r = $html_r."Posted By".$comment->comment_author." On ".$comment->comment_date. "";
endforeach;
return $html_r;
}
add_shortcode('woo_reviews', 'get_woo_reviews');
And it works just fine when I add the short code [woo_reviews]
to this test page.
How do I change this to get only 5 random reviews?
Also How would I format this page now to make it only 5 reviews and be able to change the appearance of the reviews on the page (spacing, font etc)?
2
Answers
Add the follows code snippets –
With the comment
WP_Comment_Query
, comments can’t be in random order. so you need to use a simple lightweight SQL query instead, using dedicated WordPressWPDB
Class.In the following code, you can change the styles and the html structure to get the desired output. You can also set the number of reviews you want to display in random order using available shortcode argument “limit” (default is set to 5):
Code goes in function.php file of your active child theme (or active theme). Tested and works.
USAGE:
[woo_reviews]
or in php:echo do_shortcode( "[woo_reviews]" );