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');