0

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.

User_FTW
  • 504
  • 1
  • 16
  • 44

1 Answers1

1

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')
    )
trex005
  • 5,015
  • 4
  • 28
  • 41
  • Thanks. That works and answers my question. But I've since learned that some meta_values are NULL (I noticed while I was in PHPMyAdmin). How would I modify that to include NULL meta_values? – User_FTW Apr 15 '16 at 07:51
  • I don't have a WP instalation I can play with to test, but I'd try adding another array : `array( 'key' => 'the_status', 'value' => NULL )` – trex005 Apr 15 '16 at 07:59
  • That didn't work (though I agree it should have). I'm open to alternative suggestions. I've marked your original answer as correct though. Thanks! – User_FTW Apr 15 '16 at 08:56
  • well, it's ugly, but you could 1. echo the query to figure out how it's joining the postmeta table 2. add a filter to `posts_where` 3. Run your query 4. remove the filter – trex005 Apr 15 '16 at 09:03