I'm trying to display a random comment from specific posts on my homepage, using the solution that was provided here:


It works, but it pulls a random comment from a random post, instead of selecting the post I point at with the shortcode. Does anyone know how to fix this?

add_shortcode( 'randomComment', 'randomComment_handler' );

function randomComment_handler($post_id) {
extract( shortcode_atts( array(
    'post_id' => '0',
    ), $atts ) );
$out = "";
$comments = get_comments("post_id=$post_id&status=approve");
if ($comments) {
    $ndx = mt_rand(0,sizeof($comments)) - 1; 
    $comment = $comments[$ndx];
    $out = "<div class='randomComment'><div class='randomAuthor'>".$comment->comment_author."</div><div class='randomText'>".$comment->comment_content."</div></div>";
return $out;

and the shortcode:

[randomComment post_id="463"]

The main issue with the code snippet is this line:

function randomComment_handler($post_id) {

Check out the Codex on add_shortcode() and see if you can find the error.

Spoiler: It should be like this:

function randomComment_handler( $atts, $content = NULL ) {

ps: You should also avoid using extract(), use $atts['post_id'] instead.

Further consider adding the third parameter to the shortcode_atts() function.

  • excellent, thanks for this solution, works like a charm! can check on memstories.com frontpage – dbj Feb 4 '14 at 9:17
  • sorry for the late response, but where do I mark as accepted? [edit: found it.. :)] – dbj Jul 16 '14 at 6:29

protected by Community Sep 24 '15 at 13:36

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.