As already stated, this functionality is not natively supported by Wordpress, but that does not say it can't be done.
To accomplish this, you'll need to add a custom query_vars
, and add custom sql queries and joining these queries through the posts_join
posts_orderby
filters. This code was stripped from the Filter By Comments plugin from Kevin Ingersoll. The complete plugin can be downloaded here. I've tested it thoroughly, and it works despite not being updated in more than two years.
Here is the custom code that makes it all happens
<?php
FilterByComments::getInstance();
class FilterByComments {
static function getInstance() {
static $instance;
return $instance ? $instance : $instance = new self;
}
private function __clone() {}
protected function __construct() {
add_filter('query_vars', array(&$this, 'query_vars'));
add_filter('posts_join', array(&$this, 'posts_join'));
add_filter('posts_orderby', array(&$this, 'posts_orderby'));
}
function query_vars($vars) {
$vars[] = 'orderby_last_comment';
return $vars;
}
function posts_join($sql) {
global $wpdb;
if(get_query_var('orderby_last_comment')) {
return $sql.'
LEFT JOIN (SELECT `comment_post_ID` AS `post`, MAX(`comment_date`) AS `date` FROM `'.$wpdb->comments.'` WHERE `comment_approved`="1" GROUP BY `post`) AS `last_comment`
ON `last_comment`.`post` = `'.$wpdb->posts.'`.`ID`
';
}
return $sql;
}
function posts_orderby($sql) {
if(get_query_var('orderby_last_comment')) {
return '`last_comment`.`date` DESC'.($sql !== '' ? ', '.$sql : '');
}
return $sql;
}
}
?>
It is simple to implement via pre_get_posts
or WP_Query
.You can work directly with the query_vars
orderby_last_comment
. To order posts by newest comment, just set orderby_last_comment
to true
or 1
USING pre_get_posts
function order_by_newest_comment( $query ) {
if ( $query->is_main_query() && $query->is_home() ) {
$query->set( 'orderby_last_comment', true );
}
}
add_action( 'pre_get_posts', 'order_by_newest_comment' );
USING WP_Query
$the_query = new WP_Query('orderby_last_comment=true');