Hi there!
Based on something I played with a long time ago, here’s a revised version that should do what you need:
add_action( 'pre_get_posts', 'sort_by_most_viewed' );
function sort_by_most_viewed( $query ){
global $wp_query;
// Run this only on the front-end, leave the admin side alone
if ( !is_admin() && $query->is_main_query() ) {
// Ignore sticky posts
$query->set( 'ignore_sticky_posts', true );
add_filter( 'posts_fields', 'wpp_query_fields' );
add_filter( 'posts_join', 'wpp_query_join' );
add_filter( 'posts_where' , 'wpp_query_where' );
add_filter( 'posts_groupby', 'wpp_query_group_by' );
add_filter( 'posts_orderby', 'wpp_query_order_by' );
}
}
function wpp_query_fields( $fields ){
global $wpdb;
$fields .= ", SUM({$wpdb->prefix}popularpostsdata.pageviews) AS pageviews";
return $fields;
}
function wpp_query_join( $join ){
global $wpdb;
$join .= " LEFT JOIN {$wpdb->prefix}popularpostssummary ON " . $wpdb->posts . ".ID = {$wpdb->prefix}popularpostssummary.postid ";
return $join;
}
function wpp_query_where( $where ){
global $wpdb;
$now = current_time('mysql');
$where .= " AND {$wpdb->prefix}popularpostssummary.last_viewed > DATE_SUB('{$now}', INTERVAL 1 MONTH) ";
return $where;
}
function wpp_query_group_by( $groupby ){
global $wpdb;
$groupby = "{$wpdb->prefix}popularpostssummary.postid";
return $groupby;
}
function wpp_query_order_by( $orderby ){
return "pageviews DESC";
}
I didn’t test this, though. Give it a try and let me know how it goes, alright?