I want to sort search results by the value of custom field (‘name-official’) for all posts (is this field filled or not).
But when I add filter in function.php like

function searchExcludePages($query) {
    if ($query->is_search) {
        $query->set('orderby','meta_value');
        $query->set('meta_key','name-official');
        $query->set('order','ASC');
    }
    return $query;
}
add_filter('pre_get_posts','searchExcludePages');

i’ve received results with filled ‘name-official’ only. What should i do to get results with non-filled field too?


$query->set(
            'meta_query',
            array(
                'relation' => 'OR', # Matches to this meta_query should be added to those matching the 'meta_key' query
                array(
                    'key' => 'name-official',
                    'value' => 'non-exist-value',
                    'compare' => 'NOT EXISTS'
                )
            )
        );

        $query->set('orderby','meta_value date');
        $query->set('meta_key','name-official');       
        $query->set('order','DESC');

0

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *