admin管理员组文章数量:1315258
How can I build a query to find posts that DO NOT contain a certain meta key or meta value?
for example:
query_posts( array(
'meta_query' => array(
array( 'key' => 'feature', 'value' => '_wp_zero_value', 'compare' => '!=' ) )
) );
How can I build a query to find posts that DO NOT contain a certain meta key or meta value?
for example:
query_posts( array(
'meta_query' => array(
array( 'key' => 'feature', 'value' => '_wp_zero_value', 'compare' => '!=' ) )
) );
Share
Improve this question
edited Jun 28, 2011 at 23:56
TheDeadMedic
36.7k9 gold badges68 silver badges102 bronze badges
asked Jun 28, 2011 at 23:54
dwenausdwenaus
1,2512 gold badges13 silver badges24 bronze badges
2 Answers
Reset to default 9Getting posts without a certain meta key is a little tricky, namely due to the database design and the nature of SQL joins.
AFAIK, the most efficient way would be to actually grab the post IDs that do have the meta key, and then exclude them from your query.
// get all post IDs that *have* 'meta_key' with a non-empty value
$posts = $wpdb->get_col( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = 'my_key' AND meta_value != ''" );
// get all posts *excluding* the ones we just found
query_posts( array( 'post__not_in' => $posts ) );
$args = array(
'meta_query' => array(
'relation' => 'OR', //default AND
array(
'key' => 'feature',
'compare' => 'NOT EXISTS'
),
array(
'key' => 'feature',
'value' => '_wp_zero_value',
'compare' => '='
)
));
$the_query = new WP_Query($args);
var_dump($the_query);
Read further : Wordpress Doc
NB: before the wordpress 3.9 there is a bug So this is the work around
array(
'key' => 'feature',
'compare' => 'NOT EXISTS',
'value' => '' //add this empty value check for check NOT EXISTS
),
本文标签: wp queryhow to show posts that are missing a metavalue
版权声明:本文标题:wp query - how to show posts that are missing a meta_value 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741961620a2407311.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论