I like to exclude certain posts with a custom field. So if my_custom_field_ignore isset AND 1 ignore this post. If it’s not set include it.

This is what I have

    $args = array(
        'post_type' => $post_type,
        'offset' => $offset,
        'meta_query' => array(
            array(
                'key' => 'my_custom_field_ignore',
                'value' => '1',
                'compare' => '!=',
            )
        )
    );

This works only for posts where the my_custom_field_ignore is set to something else than 1

How can I include all posts (of course not the ones with my_custom_field_ignore = 1)?

Edit:

This is how it work on WP 3.5+

    'meta_query' => array(
        array(
            'key' => 'my_custom_field_ignore',
            'compare' => 'NOT EXISTS',
        )
    )

This simple search for the appearance of my_custom_field_ignore so the value will be ignored. While this could work in the first place users may get confused when they changed 1 to 0 and expect to be included.

Seems 3.3 and 3.4 needs some conditional check though.

Edit 2

Seems the checked answered does the trick (at least for 3.5+). For some odd reason it ignores the very first post “Hello World”. After adding my_custom_field_ignore and removing it afterwards it’s working

2 s
2

If we define the conditions:

A: my_custom_field_ignore EXISTS
B: my_custom_field_ignore = 1

then NOT ( A && B ) is equivalent to:

NOT ( A ) || NOT ( B )

meaning in our case:

( my_custom_field_ignore NOT EXISTS ) ||  ( my_custom_field_ignore != 1 ) 

We could therefore try the following for WP 3.5+ (untested):

 $args = array(
    'post_type'  => $post_type,
    'offset'     => $offset,
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key'     => 'my_custom_field_ignore',
            'value'   => '1',
            'compare' => '!=',
        ),
        array(
            'key'     => 'my_custom_field_ignore',
            'compare' => 'NOT EXISTS',
            'value'   => '1',     #<-- just some value as a pre 3.9 bugfix (Codex)
        ),
    )
);

Leave a Reply

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