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)
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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' );
}
});
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
Method 2
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);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0