Sorting posts DESC based on the number of comments using WP_Query

I have this unusual requirement from my client that I need to accommodate. They want to be able to view the posts with the largest number of comments first.

At first I thought using a custom select query would do the trick. I had to write a subquery to but was able to use a custom select query to implement the functionality. Well, it didn’t take me too long to realize that suddenly the WP Page Numbers plugin stopped working. Looking at the source code for the plugin I realized it’s relying on the WP_Query object having been populated in order to figure out the page numbers and navigation stuff.

Read More

I can’t think of a way to use the WP_Query class to do the kinds of sorting I need to do. At the same time, I don’t want to have to implement my own pagination functionality because my client (and I) really love the WP Page Numbers plugin.

Before I go down the path of extending the WP_Query class as Mike suggested in this post, I just wanted to reach out to everyone with similar experiences and ask if there is any alternatives. Thanks!

Related posts

Leave a Reply

2 comments

  1. The comments already contain an answer to this question, which is:

     query_posts( 'orderby=comment_count' );
    

    Now, here is a basic equivalent code to use with the WP_Query class, since everyone knows not to use query_posts:

    $query = new WP_Query( array( 'orderby' => 'comment_count') );