How To: Rearrange WordPress Comments (Latest On Top)

A few days ago i had to make a minor change to my friend’s site, he wanted the latest comments to be right on top instead of the usual at the bottom of a page, so I had to re-arrange how the comments appeared and if for some reason you need this function all you have to do is a minor edit of /wp-includes/comment-template.php.

Original Code:

// TODO: Use API instead of SELECTs.

if ( $user_ID) {

$comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = '$post->ID' AND (comment_approved = '1' OR ( user_id = '$user_ID' AND comment_approved = '0' ) ) ORDER BY comment_date");

} else if ( empty($comment_author) ) {

$comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = '$post->ID' AND comment_approved = '1' ORDER BY comment_date");

} else {

$author_db = $wpdb->escape($comment_author);

$email_db = $wpdb->escape($comment_author_email);

$comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = '$post->ID' AND ( comment_approved = '1' OR ( comment_author = '$author_db' AND comment_author_email = '$email_db' AND comment_approved = '0' ) ) ORDER BY comment_date");

}

Amazingly enough all you have to do is add a four letter word… DESC :

// TODO: Use API instead of SELECTs.

if ( empty($comment_author) ) {

$comments = $wpdb->get_results(”SELECT * FROM $wpdb->comments WHERE comment_post_ID = ‘$post->ID’ AND comment_approved = ‘1′ ORDER BY comment_date DESC“);

} else {

$author_db = $wpdb->escape($comment_author);

$email_db = $wpdb->escape($comment_author_email);

$comments = $wpdb->get_results(”SELECT * FROM $wpdb->comments WHERE comment_post_ID = ‘$post->ID’ AND ( comment_approved = ‘1′ OR ( comment_author = ‘$author_db’ AND comment_author_email = ‘$email_db’ AND comment_approved = ‘0′ ) ) ORDER BY comment_date DESC“);

}

That’s it!

UPDATE: I fired up my Dreamwever and can confirm that you’ll find the code in just about line 290

{ 1 comment }

LEE September 2, 2010 at 2:54 pm

Thank you for review a valuble article. This useful for me and my friend, I will follow your blog for continue reading your news.

Comments on this entry are closed.

Next post: