I have a random comment script for WordPress that I’ve been using as a widget. It has worked fine for showing just one comment but now I need it to show three. I tried just adding new variables and output copying the existing code but the possibility of it generating the same comment multiple times is a lot more often than I thought it would be. Any suggestions would be appreciated.
Here’s the original code for showing just one comment:
<div style="width:276px;margin:0 15px">
<h2>Testimonials</h2>
<div style="background:rgba(65, 115, 148, 0.3);border-radius:0 0 6px 6px;height:265px;border:1px solid #ddd;box-shadow:0 0 3px #fff;padding:5px;overflow-y:auto">
<?php
$post_id = 276; // Put the 'testimonials' id here
$comments = get_comments("post_id=$post_id&status=approve");
if ($comments) {
$ndx = mt_rand(2,sizeof($comments)) - 1;
$comment = $comments[$ndx];
?>
<p style="margin-bottom:20px">
<span style="float:left;margin-right:3px"><?php echo get_avatar($comment->comment_author_email, 48, $default, $alt ); ?></span>
<?php
if (empty($comment->comment_author)){echo "$comment->comment_author";}
else{echo "<a href='$comment->comment_author_url'>$comment->comment_author</a>";}
?>
- <?php echo "$comment->comment_date"; ?><br />
<?php echo "$comment->comment_content"; ?></p>
<span style="float:right;margin-right:3px;"><?php echo "$comment1->extra_sitename"; ?></span>
<?php } ?>
</div>
</div>
Perhaps another approach.
Lets say you construct an array of available comments ids.
Then you can use array_rand() to get 3 random ids of this array.
Then you can get your data from db based on selected ids.
Is this close to what you look for?
EDIT: 2nd solution
You can get 3 random records directly from database.
If we “unset” the chosen random value from the array, we can select another one without fear of duplication. Note that I’m starting
mt_rand
from zero and subtracting1
fromsizeof
.