wp query - Pre get posts sort by meta key returns no results if meta key does not exist

admin2025-06-04  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');

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');
Share Improve this question asked Jan 17, 2019 at 2:46 rhysclayrhysclay 3704 silver badges10 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748998712a315494.html

最新回复(0)