How can I use order_by to order by two meta_keys without excluding posts that don’t have those keys initialized?

I had a similar issue but couldn’t solved with the snippets on this thread.

I had to order a query by:

  1. all ‘featured’ posts first (is_it_a_featured_etf) and
  2. by a numeric field (etf_aum) in DESC order after the featured ones.

My solution:

'meta_query'   => [
  'relation'    => 'OR',

  'etf_aum'    => array(
    'key'     => 'etf_aum',
    'type'    => 'NUMERIC',
    'compare' => 'EXISTS',
  ),

  'is_it_a_featured_etf' => array(
    'key'       => 'is_it_a_featured_etf',
    'compare'   => 'EXISTS',
    'value'     => '1',
    'operator'  => '=',
  ),
],
'orderby' => [
  'is_it_a_featured_etf' => 'ASC',
  'etf_aum' => 'DESC',
]

Leave a Comment