Lucas Jahn
Lucas Jahn

Reputation: 306

Wordpress Query - Order by meta_value_num AND date

im a bit stuck at the moment with the order in my wp_query.

I want to sort a query firstly by meta_value_num (this works perfect) AND as fallback by the date. But in my query the date seems dominant in comparision with the meta_value_num.

So it sorts all my posts by date and then apllys the meta_num_value order and not vice versa.

Do you have any clue how to do this?

$args = array(
    'post_type' => 'anbieter',
    'showposts' => -1,
    'order' => 'DESC',
    'orderby' => 'meta_value_num date',
    'meta_key' => 'rating'
);

I found so many threads to order by two custom fields but not to sort by by "normal post field" AND custom field.

regards,

Upvotes: 1

Views: 3333

Answers (1)

danyo
danyo

Reputation: 5846

I found a solution a while ago which was this. Add this to your functions.php:

function wdw_query_orderby_postmeta_date( $orderby ){
    $new_orderby = str_replace( "wp_postmeta.meta_value", "STR_TO_DATE(wp_postmeta.meta_value, '%d-%m-%Y')", $orderby );
    return $new_orderby;
}

Then do this with your query:

add_filter( 'posts_orderby', 'wdw_query_orderby_postmeta_date', 10, 1);
$args = array(
    'post_type' => 'anbieter',
    'showposts' => -1,
    'order' => 'DESC',
    'orderby' => 'meta_value',
    'meta_key' => 'rating'
);
remove_filter( 'posts_orderby', 'wdw_query_orderby_postmeta_date', 10, 1);

Upvotes: 1

Related Questions