How to order posts by descending comment count on taxonomy page?

This lists the posts in my custom taxonomy template page:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

How can I order those posts by comment count?

Related posts

Leave a Reply

2 comments

  1. A friend helped me with a solution that I could place in my functions.php file:

    add_filter( 'pre_get_posts', 'my_pre_get_posts' );
    
    function my_pre_get_posts( $query ) {
    
        if ( is_tax( 'locations' ) && empty( $query->query_vars['suppress_filters'] ) )
            $query->set( 'orderby', 'comment_count' );
    
        return $query;
    }
    
  2. WP Query has a comment_count parameter since 2.9.

    So:

    query_posts(array('orderby' => 'comment_count', 'posts_per_page' => '10'));
    if ( have_posts() ) : while ( have_posts() ) : the_post();