Secondary Sort (fallback) for WP_Query

What I’m after is creating a secondary (or default) orderby option for a custom query. Here is what I have:

$post_args = array(
    'post_type' => $taxfunc_post_type,
    'meta_key'  => '_mouldings_dimensions_height',
    'orderby'   => 'meta_value_num',
    'order'     => 'ASC',
    'paged'     => get_query_var('paged'),
    'tax_query' => array(
        array(
            'taxonomy'         => $taxfunc_tax_name,
            'field'            => 'id',
            'include_children' => 0,
            'terms'            => $term_id
        )
    ),
    'meta_query' => array(
        array(
            'key' => 'special_profile',
            'value' => $special_logic_serialized
        )
    )
);

What I’d like to do is if _mouldings_dimensions_height is NULL, then default back to title. I did see Jan’s answer on this, which does appear to be related, but I think I’m after the opposite. Ideally, I’d also be checking for just this query with query_var['post_type'] as the original questioner asked, but am not sure I am approaching this correctly. Any nudges in the right direction would be greatly apprecaited. Thanks!

Read More

Update
After a bit more testing, it appears to list the oldest first as a fallback when the meta value is the same across multiple posts (NULL in this case) — looking to change this behavior.

Related posts

Leave a Reply

1 comment

  1. It’s a quite simple revision to your current code. You can add multiple “orderby” values separated by a space.

    'orderby'   => 'meta_value_num title',
    

    This should keep the priority of sorting by your meta value, with a secondary sort of title.