How can I show comments in random order?

Never actually had a need for this but you will need to use the WP_Comment_Query function. There is this handy comments query generator online to customize this query easily.

But wait, it doesn’t allow you to select a random order. No worries just add or replace the orderby parameter:

'orderby' => 'rand'

This should return comments ordered randomly. Let me know if you need any extra tips.

Edit: the above will not work.

I should have investigated deeper into the subject. The rand argument is not accepted in a comment query, as I thought it would, it is only accepted in post queries.

So how can you achieve this behavior. You can do it in an even simpler way using a built in PHP function to randomize arrays.

You should edit the theme’s comment template, usually it is comments.php and replace the wp_list_comments() function with something like:

//optional arguments in this array, without arguments will return all comments
$args = array();
$comments = get_comments( $args );
// use shuffle to randomize the order of the comments 
shuffle($comments);

Now you need to iterate the $comments array, and do something like:

foreach ( $comments as $comment ) :
    echo $comment->comment_author . '<br />' . $comment->comment_content;
endforeach;

You can find more info on the get_comments() documentation page and the accepted arguments to customize the query.


Leave a Comment