I have two meta_keys on a custom post type. I want to be able to query all of these posts, and order them by the two meta_key, one taking precedence over the other.

I.e. I have one meta_key called stickied, these should always appear first. The second meta_key is popularity, which is a basic hit count for that post.

When I use meta_query, it seems that posts without the meta keys initialized will not appear in the result set. I want all posts regardless of whether they have the meta_key initialized or not, and then order them based on those meta_key.

Is this possible?

4 s
4

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 Reply

Your email address will not be published. Required fields are marked *