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