0

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?

1 Answer 1

1

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');
3
  • 1
    This does not work either. Could it have something to do with the fact the the '0' is the result of an unchecked checkbox?
    – Jasper
    Apr 22, 2016 at 13:54
  • No, it shouldn't. I just ran this code in a test setup and it works. Is your $query->set run? if you add a var_dump($query->get('meta_query')); at the end of the function, does it prints the meta_query array? if not it means that the if statement is true and the query is not altered
    – Kuuak
    Apr 22, 2016 at 16:52
  • Depending on your meta data save function, the value could be absent or false which might not match '0'. You could verify the value is as expected, or add back the relation clause and arrays for the other possible values like 'compare' => 'NOT EXISTS'. Oct 31, 2019 at 17:03

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.