Why isn’t my multiple orderby working?

I have a custom category page with the following query:

$args = array(  
   'cat'  => $portfolioCategories,   
   'posts_per_page'     => $itemsPerPage,  
   'orderby'            => 'menu_order date',   
   'order'              => 'DESC',   
   'paged'              => $paged   
);   
query_posts( $args );

So 'orderby' => 'menu_order' works just fine. 'orderby' => 'date' works just fine.

Read More

But 'orderby' => 'menu_order date' does not work – I get some weird completely random order.

What have I done wrong?

PS: Yes, I have enabled page attributes (ie, menu order) for posts in my functions file
PPS: I get the same results whether I use query_posts($args) or new WP_Query($args)

EDIT: The SQL generated looks like this:

SELECT SQL_CALC_FOUND_ROWS  wp_rk2ukj_posts.ID 
  FROM wp_rk2ukj_posts 
 INNER JOIN wp_rk2ukj_term_relationships ON (wp_rk2ukj_posts.ID = wp_rk2ukj_term_relationships.object_id) 
 WHERE 1=1  
   AND ( wp_rk2ukj_term_relationships.term_taxonomy_id IN (89,93,94,95,96,106) ) 
   AND wp_rk2ukj_posts.post_type = 'post' 
   AND (wp_rk2ukj_posts.post_status = 'publish' OR wp_rk2ukj_posts.post_status = 'private') 
 GROUP BY wp_rk2ukj_posts.ID
 ORDER BY wp_rk2ukj_posts.menu_order,wp_rk2ukj_posts.post_date DESC
 LIMIT 0, 9

Related posts

2 comments

  1. This should help:

    You can use multiple fields in orderby argument. Codex shows you how to do it (and you do it correctly):

    $query = new WP_Query( array( 'post_type' => 'page', 'orderby' => 'menu_order date', 'order' => 'ASC' ) );
    

    And it should solve your problem. (It should, but if you want to sort DESC it probably won’t, because of this WordPress bug: http://core.trac.wordpress.org/ticket/17065)

    Of course you always can use posts_orderby filter to create your own ORDER BY part of query.

    function my_posts_orderby($orderby_statement) {
        $orderby_statement = "YOUR ORDER BY STATEMENT";
        return $orderby_statement;
    }
    add_filter('posts_orderby', 'my_posts_orderby');
    

    Just add this filter just before you call your query and remove it after.

  2. Based on above comment from Krzysiek Dróżdż I use in my code:

     add_filter('posts_orderby', 'my_product_order_by_sort');
     $args = array( 'post_type' => 'product',  'product_cat' => $category->slug);
     $loop = new WP_Query( $args );
       .....
     remove_filter('posts_orderby', 'my_product_order_by_sort');
    

    So I added function with multiple order:

    function my_product_order_by_sort($orderby_statement) {
        $orderby_statement = "wp_posts.menu_order ASC, wp_posts.id ASC";
        return $orderby_statement;
    }
    

Comments are closed.