Search Custom Post with meta_value NULL

I need to get only the custom posts which have meta_key landing_exported as meta_value NULL.

I know that exists at least 2 custom posts in my database, but my code print “nothing found”.

$args = array(
            'post_type'     => LANDING__CUSTOM_POST,
            'meta_query' => array(
                array(
                    'key' => 'landing_exported',
                    'value' => false,
                    'type' => 'BOOLEAN'
                )
            )
        );

        // query
        $the_query = new WP_Query( $args );
        if( $the_query->have_posts() ) {

           // do funny things

        } else {

           echo 'nothing found';

        }

3 Answers
3

I depends if you’re looking for an empty value:

$args = array(
    'post_type'  => LANDING__CUSTOM_POST,
    'meta_query' => array(
        array(
            'key'     => 'landing_exported',
            'value'   => '',
            'compare' => '='
        )
    )
);

// query
$the_query = new WP_Query( $args );

which searches for value like: meta_value=""

or if you are looking for actually a NULL value which is more difficult (or I couldn’t find an easier solution):

add_filter( 'posts_where', 'my_modify_the_posts_where' );
function lets_modify_the_posts_where( $clause="" ) {
    global $wpdb;

    $clause .= " AND " . $wpdb->prefix . "postmeta.meta_value IS NULL"
    return $clause;
}

$args = array(
    'post_type'  => LANDING__CUSTOM_POST,
    'meta_query' => array(
        array(
            'key'     => 'landing_exported',
            'compare' => 'EXISTS'
        )
    )
);

// query
$the_query = new WP_Query( $args );

remove_filter('posts_where', 'my_modify_the_posts_where');

which searches for value like: meta_value IS NULL

Leave a Comment