WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

WordPress default setting is, most recent post is the first post of the blog.

But, I need to "Most commented post should be the first post in the blog". ( Categories page as well as home page)

share|improve this question
up vote 3 down vote accepted

Alex, the codex is your friend. You have a parameter orderby which you can set to order posts by comment_count. You can get the complete list of parameters accepted by orderby in the codex page about WP_Query

There is no need for any custom query, you can simply just alter the main query with the use of the action hook pre_get_posts. To order posts by comment count on the home and category pages, you can use the conditional tags is_home and is_category to target the homepage and category pages respectively.

add_action ( 'pre_get_posts', function ( $query ) 
    if (    !is_admin()
         && $query->is_main_query()
         && (    $query->is_home() 
              || $query->is_category()
    ) {
        $query->set( 'orderby', 'comment_count' );


This code should be placed in your functions.php or any file that is related to functions.php, ie, any file used for rendering functionalities like functions.php does

share|improve this answer
I am new to WordPress, but I understand the code. Can you please tell where I add this code? or where I chnage the code. Which file I shoud chnage? – Alex Jul 15 '14 at 5:28
This should go into functions.php. Just make sure it is in between the first opening <?php tag and last closing ?> php tag – Pieter Goosen Jul 15 '14 at 5:32
if($query->is_main_query() AND $query->!is_admin() ) Is above line correct? – Alex Jul 15 '14 at 5:56
Is it giving you an error. I didn't test the code – Pieter Goosen Jul 15 '14 at 6:08
@dingo_d Glad to hear this was helpful. I also update the code a bit – Pieter Goosen Feb 11 at 7:58

WP Query has a comment_count parameter since 2.9.

You can use 'orderby' => 'comment_count' in your query with other parameters, which list by number of comment count of post

  'orderby' => 'comment_count',

$my_query = new WP_Query($args);
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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