最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Query posts with "non set" meta value

programmeradmin0浏览0评论

I'd like to make a query of custom posts based on a custom field, say instrument. I need to be able to query only those posts for which the custom field has not been set (i.e. for which the meta value does not exist). Is there a way to achieve this with meta_query ? Here's the code for the query :

$args = array(
    'post_type' => 'my_custom_post_type',
    'nopaging' => true
);

$args['meta_query'] = array(
                            array(
                                'key'       => 'instrument',
                                // when value is not even set.
                            )
                        );

}

$the_query = new WP_Query( $args );

I'd like to make a query of custom posts based on a custom field, say instrument. I need to be able to query only those posts for which the custom field has not been set (i.e. for which the meta value does not exist). Is there a way to achieve this with meta_query ? Here's the code for the query :

$args = array(
    'post_type' => 'my_custom_post_type',
    'nopaging' => true
);

$args['meta_query'] = array(
                            array(
                                'key'       => 'instrument',
                                // when value is not even set.
                            )
                        );

}

$the_query = new WP_Query( $args );
Share Improve this question asked Sep 18, 2019 at 12:57 GuitarExtendedGuitarExtended 2392 silver badges10 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

As documented, you can set the compare property of the meta query to NOT EXISTS:

$args['meta_query'] = array(
    array(
        'key'     => 'instrument',
        'compare' => 'NOT EXISTS',
    ),
);

The meta query can take an argument called "compare" which can be set to "NOT EXISTS".

So your meta query should look like this:

$args['meta_query'] = array(
    array(
        'key'       => 'instrument',
        'compare'   => 'NOT EXISTS'
    )
);

The list of all arguments for the meta_query can be found in the codex: https://codex.wordpress/Class_Reference/WP_Meta_Query

发布评论

评论列表(0)

  1. 暂无评论