I want to retrieve all custom posts with a specific custom taxonomy term, and order them by a particular custom meta field. However, I also need to cater for when the orderby field is empty, and in that case, orderby date. If I orderby meta_value and include the appropriate meta_key, then if that particular category doesn't have the meta, no posts are returned at all.

USE CASE: I have a rental property custom post, and some "featured categories" (taxonomy), such as "child friendly". And there is a toggle (custom meta) to mark the post as sticky or not.

I want to retrieve (for example), all rental properties that are marked as child friendly, and order by sticky=on. However, if none of the properties are marked as sticky, then I want to orderby date.

I think the root of the problem is that, by default, if the sticky toggle is not marked as "on", then there is no meta stored in the database. There is no entry for sticky=off, the custom meta is just not there.

So, should I tweak the custom post code such that there is always a value for sticky (ie, 0/1, or on/off), or is there a way (maybe pre_get_posts?) to check the query and use a different orderby... Or perhaps there is some clever meta_query I could use?

I'm thinking the first option would be most efficient?

My current query looks like this:

$args = array(
    'numberposts'      => -1,
    'tax_query'        => array(
            'taxonomy' => 'property-feature',
            'field'    => 'slug',
            'terms'    => 'child-friendly'
    'meta_key'         => 'sticky_post',
    'orderby'          => 'meta_value date',
    'order'            => 'ASC',
    'post_type'        => 'listing',
    'post_status'      => 'publish',
    'fields'           => 'ids',
$posts = get_posts( $args );

However, this only retrieves posts if there are listings marked as sticky. What if there are none that are sticky? I still want to get those. I don't think running 2 queries (ie, if the first query is empty, then do the second query) is the best way to do this...

  • 1
    There are EXISTS / NOT EXISTS comparisons, but you may be better off moving everything to taxonomies, meta queries are pretty slow. – Milo Jan 27 '17 at 17:16
  • Well, even if I move it to a taxonomy, how would I search by one taxonomy but order by another? – Amanda Feb 2 '17 at 11:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.