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

custom post types - Meta query and compare "!=" not working as expected

programmeradmin4浏览0评论

I realize that maybe this could be an already submitted question and I searched for it, but couldn't find it.

I've got the following simple meta query:

if (!is_admin() && is_post_type_archive('custom_post') && $query->is_main_query()) {
    $meta_query = array(
        array(
            'key' => 'is_hidden',
            'value' => 'on',
            'compare' => '!='
        ),
    );
    $query->set('meta_query', $meta_query);
    $query->set('posts_per_page', -1);
}

What I expect is to get all the "custom_post" posts in the relative Archive page that DOESN'T have the "is_hidden" checkbox active (so an ''/empty value instead of 'on' -> this is the value I get from CMB2 custom field checkbox). But it doesn't work, as the result is no posts at all.

While if I set the 'compare' to "equal" ('=') it works – meaning: I get only all the posts with the "is_hidden" checkbox set to 'on'.

Maybe I'm missing something...

I realize that maybe this could be an already submitted question and I searched for it, but couldn't find it.

I've got the following simple meta query:

if (!is_admin() && is_post_type_archive('custom_post') && $query->is_main_query()) {
    $meta_query = array(
        array(
            'key' => 'is_hidden',
            'value' => 'on',
            'compare' => '!='
        ),
    );
    $query->set('meta_query', $meta_query);
    $query->set('posts_per_page', -1);
}

What I expect is to get all the "custom_post" posts in the relative Archive page that DOESN'T have the "is_hidden" checkbox active (so an ''/empty value instead of 'on' -> this is the value I get from CMB2 custom field checkbox). But it doesn't work, as the result is no posts at all.

While if I set the 'compare' to "equal" ('=') it works – meaning: I get only all the posts with the "is_hidden" checkbox set to 'on'.

Maybe I'm missing something...

Share Improve this question asked Apr 27, 2020 at 8:50 Paolo SacchettiPaolo Sacchetti 238 bronze badges 2
  • Do the posts without is_hidden set to on have another value? Or just no value at all? – Jacob Peattie Commented Apr 27, 2020 at 8:52
  • Hello jacob, ...just "no value". I've also tried to set the posts to "on" and save and then "off" again, you never know... but nope – Paolo Sacchetti Commented Apr 27, 2020 at 9:05
Add a comment  | 

1 Answer 1

Reset to default 0

I've found the solution (I suppose): looks like that the right operator in this case is "NOT EXISTS". I've noticed that in the db postmeta table I've got only the records of the "is_hidden" key with value "on"...

发布评论

评论列表(0)

  1. 暂无评论