I want to select posts and custom post type with a specific meta value (mb_home!=0), of last week and ORDER them by mb_home. If they have the same mb_home value, I want them to be ordered by date. Both order have to be DESC.

I am using this query but it just does not work:

$query = new WP_Query( array(
            'post_type' => array ('post', 'aggregato'),
            'posts_per_page' => 13,
            'post__not_in' => $linked_posts,
            'meta_key' => 'mb_home',
            'orderby' => 'meta_value_num date',
            'order' => 'DESC',
            'meta_query' => array(
                                        'key' => 'mb_home',
                                        'value' => '0',
                                        'compare' => '>',
            'date_query' => array(
                                    'after' => '1 week ago',

If I drop date and use 'order by' => 'meta_value_num' the query gives me back the results correctly ordered by mb_home DESC. But if they have the same mb_home value, they are ordered by date ASC.

If I try to change the way I order stuff, using this syntax:

'orderby' => array( 'meta_value_num' => 'DESC', 'date' => 'DESC' ),

instead of the above orderby and order statements, it just falls back to date DESC ignoring completely the mb_home value.

All these results are the same with meta_value instead of meta_value_num. Nothing changes.

Please, give me some pointers, because I've been over this for almost a month, trying everything but not succeeding.

Oh masters of wordpress! I invoke your help!!

1 Answer 1


You have to use the posts_orderby filter to do this at the mo, eg

function wpse159469_posts_orderby( $orderby, $query ) {
    return implode( ' DESC,', explode( ',', str_replace( array(' ASC', ' DESC' ), '', $orderby ) ) ) . ' DESC';

then around your query:

add_filter( 'posts_orderby', 'wpse159469_posts_orderby', 10, 2 );
$query = new WP_Query( array( // etc
remove_filter( 'posts_orderby', 'wpse159469_posts_orderby', 10 );
  • YES! Oh my God, YES! It works!!! Oh bonger I love you. Thank you thank you thank you. Just out of curiosity, what's the theory behind this solution? Aug 29, 2014 at 7:44
  • 2
    WP_Query fires a lot of filters before doing the actual query, posts_where, posts_groupby, posts_clauses, etc which can be used to manipulate the sql generated - originally intended according to the source for paging and caching manipulation but very useful generally to do specialist stuff or work-arounds. In this case as you want DESC order the filter just blindly deletes any ordering and appends DESC to each comma-separated orderby field.
    – bonger
    Aug 29, 2014 at 8:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.