Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

How do we get posts where the meta key does not exist in a post. I have created a meta_key video. and i want to be able to get some posts with WP_Query where custom field video does not exist or is blank.

$fsquery = new WP_Query( 
                        array ( 
                        'posts_per_page' => 1,
                        'featured' => 'yes',
                        'meta_key'=>'video',
                        'meta_value'=>''
                        )
                    );

this is not working.

share|improve this question

3 Answers 3

up vote 2 down vote accepted

There's actually a better solution that will (hopefully) be rolling out in WordPress 3.4 -- you can run the patch as a hotfix now if you'd like, but here's the TRAC link for the patch:

http://core.trac.wordpress.org/ticket/18158

With this, you can do ...

    $my_query = new WP_Query( 
        array( 
            'meta_query' => array( 
                array(
                    'key' => 'foo',
                    'compare' => 'NOT EXISTS'
                )
            ) 
        ) 
    );

or, swap it out for 'compare' => 'EXISTS' instead if you like.

-George

share|improve this answer

You can use posts_where filter hook and create a Subquery to exclude all posts with the meta_key of video:

// Create a new filtering function that will add our where clause to the query
function filter_where_WPSE_18787( $where = '' ) {

    $where .= " AND ID NOT IN ( SELECT DISTINCT post_id from $wpdb->postmeta WHERE meta_key = 'video' )";
    return $where;
}
add_filter( 'posts_where', 'filter_where_WPSE_18787' ); 

$fsquery = new WP_Query( 
    array ( 
        'posts_per_page' => 1,
        'featured' => 'yes'
        ));

remove_filter('posts_where', 'filter_where_WPSE_18787' ); 
share|improve this answer
$my_query = new WP_Query( 
        array( 
            'meta_query' => array( 
                array(
                    'key' => 'foo',
                    'compare' => 'NOT EXISTS'
                )
            ) 
        ) 
    );

used only in WP 3.5. It's still a beta version at the moment.

share|improve this answer
    
Welcome to WPSE. Glad to have you here. meta_query is also used in versions < 3.5. Also, code snippets become more useful when accompanied with an explanation. –  Brian Fegter Oct 9 '12 at 9:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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