The query you currently have will order the posts by their post_date
property, which is an SQL column of the type datetime
. This type stores the date, but also the time (hours, minutes and seconds). The second sorting option, comment_count
, is only applied to posts with the same timestamp, i.e. that were posted at the exact same second in time.
So, the solution to your problem is to sort by post date instead of datetime. To do so, you can filter the orderby
query part in WP_Query
using the filter posts_orderby
. With this filter, you can replace the SQL ORDER
clauses to use the day instead of the datetime.
The code below does this: it adds a function to the filter posts_orderby
which replaces the {$wpdb->posts}.post_date
(e.g. wp_posts.post_date
) by CAST({$wpdb->posts}.post_date AS DATE)
, which casts the datetime field to YYYY-MM-DD
format. After executing the query, it removes the filter, ensuring that other queries are not affected.
function wpse222104_query_orderby_day( $orderby, $query ) {
global $wpdb;
return str_replace( "{$wpdb->posts}.post_date", "CAST({$wpdb->posts}.post_date AS DATE)", $orderby );
}
// Add the filter to change the ORDER clause
add_filter( 'posts_orderby', 'wpse222104_query_orderby_day', 10, 2 );
// Run the query with the filters
$query = new WP_Query( $args );
// Remove the filter
remove_filter( 'posts_orderby', 'wpse222104_query_orderby_day' );
This assumes the same $args
that you already had: there was nothing wrong with them.
Testing the code
Testing the code shows that the ORDER BY
clause is correctly changed: the original clause was
wp_posts.post_date DESC, wp_posts.comment_count DESC
whereas the new one is
CAST(wp_posts.post_date AS DATE) DESC, wp_posts.comment_count DESC
Example
The precise time the post was published will now not be considered in sorting: only the date it was posted will. For example, consider the following posts:
Title Date Comment count
Example Post 2014-12-16 10:12:16 6
Another one 2014-12-16 21:50:07 4
Yet Another 2012-08-02 11:15:20 25
Here, your original query would return the posts in the order
- Another one
- Example post
- Yet another
Whereas the new code would return the posts in order
- Example post
- Another one
- Yet another
as “Example post” and “Another one” were posted on the same day, but “Example post” has more comments.