【问题标题】:Show posts that have a with a certain meta_key value or not meta_key at all显示具有特定 meta_key 值或根本没有 meta_key 的帖子
【发布时间】:2016-04-15 07:22:23
【问题描述】:

我有这个循环,我需要显示具有特定元值的帖子的所有标题,或者没有元键“the_status”。

我的帖子目前使用名为“the_status”的元键,并且可以具有以下任一元键值:

帮助 not_helping 完成_帮助

...或者帖子甚至可能根本没有 meta_key 'the_status'。

这是我所拥有的:

<?php
$the_query = array(
    'posts_per_page'    => -1, 
    'author'            => $current_user->ID,
    'post_status'       => 'publish',
    'meta_key'          => 'the_status',
    'meta_value'        => array('helping')
);
$help_posts = new WP_Query($the_query);
while($help_posts->have_posts()) : $help_posts->the_post();
?>

<p><?php the_title(); ?></p>

<?php
endwhile;
?>

这显然只给了我带有 meta_value 'helping' 的帖子的标题,但它还需要显示根本没有 meta_key 'the_status' 的帖子的标题。

感谢阅读。

【问题讨论】:

    标签: arrays wordpress loops meta-key


    【解决方案1】:

    替换

    'meta_key'          => 'the_status',
    'meta_value'        => array('helping')
    

    'meta_query' => array(
        'relation' => 'OR',
        array(
           'key' => 'the_status',
           'compare' => 'NOT EXISTS',
           'value' => '' //can be omitted in WP 3.9+
        ),
        array(
           'key' => 'the_status',
           'value' => array('helping')
        )
    

    【讨论】:

    • 谢谢。这有效并回答了我的问题。但后来我了解到一些 meta_values 是 NULL(我在 PHPMyAdmin 时注意到了)。我将如何修改它以包含 NULL meta_values?
    • 我没有可以用来测试的 WP 安装,但我会尝试添加另一个数组:array( 'key' =&gt; 'the_status', 'value' =&gt; NULL )
    • 那没有用(尽管我同意它应该有)。我愿意接受其他建议。不过,我已将您的原始答案标记为正确。谢谢!
    • 好吧,这很难看,但您可以 1. 回显查询以了解它如何加入 postmeta 表 2. 将过滤器添加到 posts_where 3. 运行您的查询 4. 删除过滤器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 2021-12-04
    • 2017-03-31
    相关资源
    最近更新 更多