Question

I'm trying to build a query in order to sort some posts by a date custom field, where the dates are formatted dd/mm/yyyy.

It works by querying the database directly with get_results like in this example :

$querystr = "
    SELECT *
    FROM wp_posts, wp_postmeta
    WHERE wp_posts.ID = wp_postmeta.post_id
    AND wp_postmeta.meta_key = 'my_cutom_date'
    AND wp_posts.post_status = 'publish'
    AND wp_posts.post_type = 'post'
    ORDER BY STR_TO_DATE(wp_postmeta.meta_value, '%d/%m/%Y') ASC
";

But, I would like to transpose this behavior to a WP_Query, using a posts_where filter. I got as far as this :

$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 10,
    'meta_key' => 'my_custom_date'
); 

function filter_orderby( $orderby = '' ) {  
    global $wpdb;
    $orderby .= " ORDER BY STR_TO_DATE($wpdb->postmeta.meta_value, '%d/%m/%Y') ASC ";
    return $orderby;
}

add_filter( 'posts_orderby', 'filter_orderby' );

But it doesn't seem to return anything. what am I missing ?

Was it helpful?

Solution

The filter on posts_orderby should return a string that does not begin with ORDER BY, WordPress will add that itself.

By default WordPress will filter by post_date. If you don't want that, you should overwrite the order clause, not append to it. So your filter should look like this:

function filter_orderby( $orderby ) {  
    global $wpdb;
    return " STR_TO_DATE({$wpdb->postmeta}.meta_value, '%d/%m/%Y') ASC ";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top