4

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');
5
  • I remember having a similar problem. I solved it by adding an empty meta_data value to all posts which didn't have the meta_data... I'll do some research to see if there is a better option as I find this quite interesting.
    – Christine Cooper
    Commented Jul 22, 2016 at 10:26
  • Oh right, you have this entire thread which discussed this issue: wordpress.stackexchange.com/questions/102447/…
    – Christine Cooper
    Commented Jul 22, 2016 at 10:27
  • Thanks for reply! Yes, i can add this meta_data everywhere but it is not good solution. About link - i've tried it, but with such code i don't see any results.
    – Varro
    Commented Jul 22, 2016 at 11:12
  • Do you have the updated code that tried the linked solution? It looks to me like it should work, perhaps with a little debugging for specific cases. Commented Jul 22, 2016 at 12:56
  • Yes, i've added snippet to question. It would be great if you can give some advice.
    – Varro
    Commented Jul 22, 2016 at 16:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.