Exclude posts with certain meta data from search results

I'm trying to exclude al posts with certain meta data from the search results but so far it's not working. Here's the code I'm using:

function ZoekGeenLegeItems( $query ) {
    if( is_admin() || !$query-is_search() || $query-get( 'post_type' ) != 'item' )
        return $query;

    $query-set('meta_query', array(
      'relation' = 'OR',
        array(
            'key' = 'KEY_itm_leeg'
            ,'value' = '0'
        )
    ));
    return $query;
}
add_filter('pre_get_posts','ZoekGeenLegeItems');

Any ideas, anyone?

Topic exclude meta-query Wordpress search

Category Web


First, the pre_get_posts hook is an action and not a filter.

Then the meta_query parameter should contain the relation only if there is more than one inner meta_query array (codex).

Finally you do not need to return the $query argument as it is passed by reference to your callback function.

Your code should look like this:

function ZoekGeenLegeItems( $query ) {
    if( is_admin() || !$query->is_search() || $query->get( 'post_type' ) != 'item' )
        return;

    $query->set('meta_query', array(
        array(
            'key'   => 'KEY_itm_leeg',
            'value' => '0'
        )
    ) );
}
add_action('pre_get_posts','ZoekGeenLegeItems');

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.