arrayswordpressloopsmeta-key

Show posts that have a with a certain meta_key value or not meta_key at all


I've got this loop where I need to display all the titles of posts that have a certain meta_value, or that and don't have the meta_key 'the_status'.

My posts currently use the meta_key called 'the_status' and can have either of these meta_key values:

helping not_helping finished_helping

...or a post may not even have the meta_key 'the_status' at all.

Here's what I have:

<?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;
?>

This obviously only gives me titles of posts that have a meta_value 'helping', but it also needs to show the titles of posts that don't have a meta_key 'the_status' at all.

Thanks for reading.


Solution

  • replace

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

    With

    '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')
        )