Order WordPress Posts by Most Comments


I take great delight in seeing people reply to my blog posts. I use WebMentions to collect replies from social media and other sites. But which of my posts has the most comments? Here's a snipped to stick in your functions.php file. It allows you to add ?comment-order to any WordPress URl and have the posts with the most comments on top.

PHP PHP//  Add ordering by comments
add_action( 'pre_get_posts', 'pre_get_posts_by_comments' );
function pre_get_posts_by_comments( $query ) {
    //  Do nothing if the post_status parameter in the URL is not "comment-order"
    if ( ! isset( $_GET['comment-order'] ) ) {
        return;
    }

    $query->set( "orderby", "comment_count" );  //  Default: date
    $query->set( "order", "DESC" ); //  Biggest first
}

This makes use of the pre_get_posts hook to rewrite the posts query. That means it works on most WordPress pages.

For example:

Did you find this post useful? Please leave a comment here!


Share this post on…

  • Mastodon
  • Facebook
  • LinkedIn
  • BlueSky
  • Threads
  • Reddit
  • HackerNews
  • Lobsters
  • WhatsApp
  • Telegram

What are your reckons?

All comments are moderated and may not be published immediately. Your email address will not be published.

Allowed HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <p> <pre> <br> <img src="" alt="" title="" srcset="">