0

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';

        }
5

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

1

I am not sure where are you getting that BOOLEAN type from. I don’t think it is a type supported by WP_Query.

Since meta values are always stored as text anyway, it is hard to guess what precisely do you mean by the NULL value.

You should examine what is the actual value in database, resulting from your code, and query accordingly. It might be something like 'NULL' string, or it might be empty string, or it might be unset altogether.

0
add_filter( 'posts_where',      'cb2_posts_where_allow_NULL_meta_query' );
function cb2_posts_where_allow_NULL_meta_query( $where ) {
    return preg_replace(
        "/CAST\(([a-z0-9_]+)\.([a-z0-9_]+) AS SIGNED\)\s*IN\s*\(([^)]*)'NULL'/mi",
        'CAST(\1.\2 AS SIGNED) IN(\3NULL',
        $where
    );
}
  • 1
    Please edit your answer, and add an explanation: why could that solve the problem? – fuxia Jul 10 '18 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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