0

I am able to sort my posts by a custom field ('tour_length_days'). However if this field does not exist on an existing post then it will return no results. I was hoping there was a way to conditionally check to see if that meta key has a value before adjusting the query?

Here is my code:

function apply_destinations_query_filter ($query)
{
    if (is_admin()) {
        return $query;
    }

    if (is_tax('destination') && $query->is_main_query()) {

        $query->set('meta_key', 'tour_length_days');       
        $query->set('orderby', array('meta_value' => 'ASC', 'date' => 'DESC'));
    }

    return $query;
}
add_action('pre_get_posts', 'apply_destinations_query_filter');
0

Please use 'meta_value' => 'meta_value_num' instead of 'AC'. You can also take help from documentation to see which parameters you can pass for order attribute in the query => https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.