0

I need to order a WP_Query by two meta fields: meta-order and meta-last-name. First by meta-order numerically, if blank, order by meta-last-name ASC. How do I do that, the documentation is not very clear on that. I've tried this but it does not work.

array(    
    'post_type'   => 'student',
    'post_status' => 'publish',
    'order'       => 'ASC',
    'orderby'     => 'meta_value',
    'meta_key'      => 'meta-order meta-last-name',
);
Leo Net
  • 777
  • 6
  • 15
  • Possible duplicate of [How to order by multiple meta keys?](http://stackoverflow.com/questions/17745334/how-to-order-by-multiple-meta-keys) – MarZab Sep 24 '16 at 21:55

2 Answers2

0

You will need to use the pre_get_posts action to be able to achieve this. See answers from https://wordpress.stackexchange.com/q/169999 on how to do it.

Community
  • 1
  • 1
Zoli Szabó
  • 4,366
  • 1
  • 13
  • 19
0

This worked for me:

array(
  'post_type'   => 'student',
  'meta_query'  => array(
    'relation' => 'OR',
    'custom_order_clause' => array(
      'key' => 'meta-custom-order',
      'compare' => 'LIKE',
    ),
    'last_name_clause' => array(
      key' => 'meta-last-name',
      'compare' => '=',
    ),
   ),
   'orderby' => array(
     'custom_order_clause' => 'ASC',
     'last_name_clause' => 'ASC'
   ),
 )

CAVEAT: Make sure you delete empty meta values from DB otherwise this will not work.

Leo Net
  • 777
  • 6
  • 15