Ordering posts by day (not time) AND meta value

This is what I’ve found. I’m using a filter to filter the ORDER BY on the SQL query generated by WP_Query. The filter is this posts_orderby. And with it, you can write a custom ORDER BY for the query. I’m gonna show you an example.

add_filter('posts_orderby', 'posts_orderby');

function posts_orderby($orderby_for_query) {
    $orderby_for_query = "LEFT(wp_posts.post_date, 10) DESC, wp_posts.post_title ASC";
    return $orderby_for_query;
}   

The key here is the LEFT function, it’s a MYSQL function. With this, you can “modify” the date, so MYSQL uses just the first 10 chars, so it uses the year, month and day, and not the time, which I think is what you wanted.

edit: as pointed by adelval, the DATE function could be used instead of LEFT.

You might need to remove the filter to avoid affecting other queries, you can do it like this:

remove_filter( 'posts_orderby', 'posts_orderby' );

Add that after the call to new WP_Query(). I hope this helped, if you have any doubt, ask.

EDIT: Just as recommendation, it is a good idea to avoid hardcoding the DB prefix, you can get it with this code.

global $wpdb;    
$prefix = $wpdb->prefix;

Then, just prepend that to the table names. For tablename.column

$prefix . 'tablename.column'

By default, the prefix is ‘wp_’.

To check the generated SQL query you can var_dump($name_of_query->request)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)