Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

2 Answers 2

up vote 2 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.

function orderby_comment_count( $query ) {
    if ( $query->is_home() OR  $query->is_category()){
        if($query->is_main_query() AND !is_admin() ) {
            $query->set( 'orderby', 'comment_count' );
       }
   }
}
add_action( 'pre_get_posts', 'orderby_comment_count' );

EDIT

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 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 at 5:32
    
if($query->is_main_query() AND $query->!is_admin() ) Is above line correct? –  Alex Jul 15 at 5:56
    
Is it giving you an error. I didn't test the code –  Pieter Goosen Jul 15 at 6:08
    
Yes. It gives error. then i remove "AND $query->!is_admin()" part. Then it worked. Is it a problem? What is the important of having "AND $query->!is_admin()" part? –  Alex Jul 15 at 6:18

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

$args=array(
  .......
  'orderby' => 'comment_count',
  .....    
);

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

Your Answer

 
discard

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.