• Resolved cyberlp23

    (@cyberlp23)


    Hello,

    I want to display all the posts with the custom field ‘status’ set to ‘0’ OR custom field ‘status’ not set at all (NULL or NOT EXISTS?). But I’m not really sure of the syntax.

    The following code doesn’t work: it seems to display all articles, even those with the field ‘status’ set to ‘1’ or ‘2’ for example.

    $args = array(
    	'posts_per_page' => -1,
    	'post_status'	=> 'pending',
    	'relation' => 'OR',
    	array(
    	'meta_key'	=> 'status',
    	'meta_value'	=> '0'
    	),
    	array(
    	'meta_key' => 'status',
            'meta_compare' => 'NOT EXISTS'
    	)
    );
    $the_query = new WP_Query( $args );
     if( $the_query->have_posts() ): ?>
    <?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <?php echo get_the_title(); ?>
    <?php endwhile; ?>
    <?php endif; ?>
    <?php wp_reset_query();

    Thanks for helping!

Viewing 2 replies - 1 through 2 (of 2 total)
  • What version of WP are you running? According to the Codex, there is a bug prior to 3.9 that requires a value in the meta_query in order for ‘NOT EXISTS’ to work:

    (Note: Due to bug #23268, value is required for NOT EXISTS comparisons to work correctly prior to 3.9. You must supply some string for the value parameter. An empty string or NULL will NOT work. However, any other string will do the trick and will NOT show up in your SQL when using NOT EXISTS. Need inspiration? How about ‘bug #23268’.)

    You might try adding a value just in case.

    $args = array(
    	'posts_per_page' => -1,
    	'post_status'	=> 'pending',
    	'relation' => 'OR',
    	array(
    	'meta_key'	=> 'status',
    	'meta_value'	=> '0'
    	),
    	array(
    	'meta_key' => 'status',
            'meta_compare' => 'NOT EXISTS',
            'meta_value'   => 'junk'
    	)
    );

    Thread Starter cyberlp23

    (@cyberlp23)

    Well no, I have version 4.2, but I changed the code to the following syntax, and it does work now. It seems that the ‘relation => OR’ had to be inside the meta_query.

    $args = array(
    	'posts_per_page' => -1,
    	'post_status'	=> 'pending',
    	'meta_query'	=> array(
    			'relation' => 'OR',
    		array(
    		'key'		=> 'status',
    		'value'	=> '0'
    		),
    		array(
    		'key'		=> 'status',
    		'compare' => 'NOT EXISTS'
    		)
    	)
    );
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘the_query : add 'NULL'/'NOT EXISTS' custom field’ is closed to new replies.