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"]

1 Answer 1


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, 2014 at 9:17
  • sorry for the late response, but where do I mark as accepted? [edit: found it.. :)]
    – dbj
    Jul 16, 2014 at 6:29

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