I’m trying to query for a custom post type for a gallery system. I have a checkbox to set a gallery as a “featured” gallery (set up through More Fields plugin) – if this is checked then the meta value becomes 1 and then if unchecked it becomes 0. All good. However if the box has never been checked then the meta key is never created, meaning I can’t query for NOT LIKE 1 because it doesn’t exist.

The query I want is to pull out 4 galleries that aren’t marked as ‘1’ in this meta value, but also those that don’t have this value at all. Is there a way to always give newly added posts a default value for this meta key (ie always make them 0 by default if the box is left unchecked) or is there a way to query for the key not yet being set?

My current query is:

$args = array(
                        'post_type' => 'gallery',
                        'showposts' => 4,
                        'meta_key' => 'gal-ID',
                        'order_by' => 'meta_value',
                        'order' => 'ASC',
                        'meta_query' => array( array(
                                            'key' => 'main-gal',
                                            'value' => false,
                                        ) ),
                        ) );

And I’ve tried various attempts with ‘compare’ => ‘NOT LIKE’, ‘!=’ etc etc.

Any ideas? This ticket seems to imply it’s something that ought to be sorted out:

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

Thanks!

4 s
4

That massive function was a bit scary, I got this working like so – with two arguments (that exclude the features)

$args = array(

    'meta_query' => array(
        'relation' => 'OR',
            array( // new and edited posts
                'key' => 'Set as Featured Post',
                'compare' => '!=',
                'value' => 1
            ),

            array( // get old posts w/out custom field
                'key' => 'Set as Featured Post',
                'value' => '1',
                'compare' => 'NOT EXISTS'
            ) 
        ),
    'posts_per_page' => 30

);

Leave a Reply

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