48

Three people have already tried to solve this, and we're coming up nil. I want to show only posts that have a value in the meta_key 'featured_image'.

So... if 'featured_image' is not empty, show the post. Here's the code:

      <ul>
      <?php
      $args = array(
        'showposts' => 5,
        'meta_query' => array(
          array(
            'key' => 'featured_image',
            'value' => '',
            'compare' => '!='
            )
          )
      );
      $ft_pagination = new WP_Query( $args );
      ?>
      <?php while ($ft_pagination->have_posts()) : $ft_pagination->the_post(); ?>
        <?php $ftimage = get_post_meta(get_the_id(), 'featured_image', TRUE); ?>
        <li>
          <article>
            <a href="">
            <?php if ($ftimage): ?>
              <img src="<?php bloginfo('template_directory'); ?>/timthumb.php?src=<?php echo $ftimage; ?>&w=84&h=60" alt="" />
            <?php else: ?>
              <img src="<?php bloginfo('template_directory'); ?>/timthumb.php?src=/wp-content/themes/ssv/images/review-default.gif&w=84&h=60" alt="" />
            <?php endif; ?>
            </a>
          </article>
        </li>
      <?php
      endwhile;

      wp_reset_query();
      ?>
      </ul>

We have tried literally every combination we can think of, the deprecated meta_* options, query_posts, get_posts, instead of WP_Query... Nothing. Printed the select statement, no meta value field is showing. It exists - for the posts (for every post) and it exists in the db.

We've seen every post out there on the topic right now, including these:

query_posts and only show results if a custom field is not empty

http://scribu.net/wordpress/advanced-metadata-queries.html

Zilch. Please help...

3
  • Which version of WordPress are you using? Mar 2, 2011 at 6:09
  • @MikeSchinkel - Sorry Mike, didn't see this — It's 3.1.
    – robalan
    Mar 2, 2011 at 6:32
  • WP 3.5 fixes this problem and lets you use a different compare method
    – Erenor Paz
    Dec 6, 2017 at 17:19

10 Answers 10

6

Hi @Rob:

The reason you can't figure out how to do it is because it's not possible, at least not without resorting to SQL. Try adding the following to your theme's functions.php file:

add_filter('posts_where','yoursite_posts_where',10,2);
function yoursite_posts_where($where,$query) {
  global $wpdb;
  $new_where = " TRIM(IFNULL({$wpdb->postmeta}.meta_value,''))<>'' ";
  if (empty($where))
    $where = $new_where;
  else
    $where = "{$where} AND {$new_where}";
  return $where;
}

If you have custom 'featured_image' fields with empty values the above will filter them out. If you problem is something else, we'll have to see what your data looks like to solve it.

One thing I'm curious about; how did you get empty values for 'featured_image'? The admin UI in WordPress 3.1 does its best to keep you from entering empty values. Hope this helps.

8
  • Thank god... so it's not just us. That's good to know, I suppose. Thank you @MikeSchinkel - They really ought to put that in the codex... Looking forward to the explanation. Thanks!!
    – robalan
    Mar 2, 2011 at 6:10
  • @Rob - So I was going off my 3.0 knowledge and now I'm testing it in 3.1 and it does seem to work. I have two posts and one with a featured_image custom field and your query works fine. What are you finding? Is there a chance your query is loading posts that do have a featured_image custom field but where the value for that field is empty? Mar 2, 2011 at 6:45
  • @MikeSchinkel - No kidding? Yes, that's exactly what it's doing — every post has the featured_image field, they're just not all set. It's loading up all posts anyway.
    – robalan
    Mar 2, 2011 at 7:20
  • @Rob - See my updated answer. Mar 2, 2011 at 7:48
  • @MikeSchinkel - Thank you! It seems to be working perfectly, after setting the post_type in the query also. The empty values are purposeful — not every post has this featured image (and I know about the post thumbnail, it's just not a good option for this site). Thanks so much!
    – robalan
    Mar 2, 2011 at 15:14
64

This seems to work for getting the value into the query, not sure about whether it pulls valid results though..

'meta_query' => array(
    array(
        'key' => 'some_key',
        'value'   => array(''),
        'compare' => 'NOT IN'
    )
)

Not had time to create fields to test the results, but i've been watching queries i've worked with today and noticed NOT IN will happily take an empty array.

4
  • I know this is an old answer, but for those trying this apparoach, it works with 'compare' => 'NOT LIKE' instead of 'NOT IN' Jul 11, 2012 at 17:10
  • 3
    Surely more efficient to use != instead of not in or not like. Same as wordpress.stackexchange.com/a/10286/32863 (that is about meta keys, but same principle)
    – Adam
    Sep 9, 2015 at 19:22
  • 6
    Even cleaner solution: like Adam stated already. Is to use: 'value' => '', 'compare' => '!=' Apr 20, 2018 at 8:32
  • If you need to check to make sure it's not an empty array... 'value' => array('', array(), serialize(array())), 'compare' => 'NOT IN'
    – StephanieQ
    Aug 14, 2018 at 16:39
25

This is an old question, but it seems Wordpress has fixed this "missing feature": now, according to Wordpress Codex is possible to check for existence (or non-existence) of the meta key, like this

'meta_query' => array(
    array(
        'key' => 'featured_image',
        'compare' => 'EXISTS', //or "NOT EXISTS", for non-existance of this key
    )
)

This is available as of WP >= 3.5.

2
  • 4
    EXISTS will show empty values which is not what we're after here. The best solution is 'value' => '', 'compare' => '!=' as far as my testing goes.
    – Ben
    Aug 9, 2019 at 13:28
  • 3
    @Ben That's exactly what the OP tried, but without any success, it seems. I added my solution to make sure people passing by searching for a method to retrieve posts based on existence of meta_key could find it. Since the value of a meta can be "something", "empty" or "null" (in case the meta doesn't exist), probably the best solution would be to merge the two options with an "AND" relation
    – Erenor Paz
    Aug 9, 2019 at 16:06
11

If you want the meta value to exist and have some value other than an empty string:

      'meta_query' => [
        'relation' => 'AND',
        [
          'key' => 'some_key',
          'compare' => 'EXISTS',
        ],
        [
          'key' => 'some_key',
          'compare' => '!=',
          'value' => ''
        ]
      ]
2
  • 3
    This is the only 100% correct answer according to my tests.
    – alexg
    Jan 5 at 14:57
  • I tried all the solutions & this one is only worked. Aug 1 at 2:13
8

This is the query that worked for me. Very similar to the comparison in t31os's answer from 2011, but because the meta key/value is just a simple textstring, it doesn't need to be a meta_query array.

$args = array(
    'posts_per_page' => 5,//replaced 'showposts' in version 2.1
    'meta_key' => 'featured_image',
    'meta_value' => array(''),
    'meta_compare' => 'NOT IN'
);

For whatever reason, using 'meta_value' => '' (set to an empty string) and 'meta_compare' => '!=' or 'meta_compare' => 'NOT LIKE' still pulled all posts for me, but it probably has something to do with the fact that I created my meta value using the Advanced Custom Fields (ACF) plugin.

While using EXISTS may work, it does not check if the value is empty or not, so it'd still pull posts that have the meta field even if the meta value is blank or empty.

Read more about custom field parameters in the codex. Possible values for meta_compare:

  • =
  • !=
  • > - works with numeric, DATE, and DATETIME meta value types
  • >= - works with numeric, DATE, and DATETIME meta value types
  • < - works with numeric, DATE, and DATETIME meta value types
  • <= - works with numeric, DATE, and DATETIME meta value types
  • LIKE - can work with an array of meta values
  • NOT LIKE - can work with an array of meta values
  • IN - meta value should be an array of values
  • NOT IN - meta value should be an array of values
  • BETWEEN - works with numeric, DATE, and DATETIME meta value types as well as an array of values
  • NOT BETWEEN - works with numeric, DATE, and DATETIME meta value types as well as an array of values
  • EXISTS - no need to specify a meta value for WP versions 3.9 and above
  • NOT EXISTS - no need to specify a meta value for WP versions 3.9 and above
  • REGEXP
  • NOT REGEXP
  • RLIKE
0
4

Am i missing something?

<?php 
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => -1,
        'meta_key' => "featured_image"
    );
    $the_query = new WP_Query( $args ); 

?>

Won't that do it?

8
  • Edit: from the codex: $query = new WP_Query( 'meta_key=featured_image' ); look here:codex.wordpress.org/Class_Reference/… Jan 24, 2014 at 21:50
  • First, you can always edit a question or answer instead of adding a comment. Second: Don't misuse answers instead of comments.
    – kaiser
    Jan 25, 2014 at 0:05
  • If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context.
    – kaiser
    Jan 25, 2014 at 0:05
  • @kaiser - seems to me like he was answering. He's not asking if his code is valid, but I suppose sort of sarcastically answering the question with what he believes will work.
    – Nathan
    Sep 5, 2016 at 4:19
  • @Nathan This is what comments are for.
    – kaiser
    Sep 5, 2016 at 7:42
3

This is fixed in WP 3.2-alpha:

http://core.trac.wordpress.org/ticket/15292

0

Hopefully this may help. You could always use the 'EMPTY' or 'NOT EMPTY' comparator like so:

       'meta_query' => [
        'relation' => 'AND',
        [
          'key' => 'your_key',
          'compare' => 'NOT EMPTY',
        ],
     
      ]

Use this with one of my checkbox ACF fields which seems to work really well. In my case, I was doing the opposite of yourself and some of the posts I was querying didn't have an entry for this meta field so I simply added the NOT EXISTS option as a second comparison.

Querying posts that either did not contain the meta field or contained an empty field:

 'meta_query' => [
        'relation' => 'AND',
        [
          'key' => 'your_key',
          'compare' => 'NOT EXIST',
        ],
        [
          'key' => 'your_key',
          'compare' => 'EMPTY',
        ],
     
      ]
1
  • I can't find the documentation for 'EMPTY' and 'NOT EMPTY'. Do you have a link to it? Jul 23 at 9:40
0

So I had this problem specifically when using ACF & when using a field that held a multiple select that had previously had been populated and now was empty.

I had the issue that:

    'relation' => 'AND',
    array(
       'key' => 'field_name',
       'compare' => 'EXISTS'
    ),    
    array(
      'key' => 'field_name',
      'value' => '',
      'compare' => '!='
    ),

Was returning all the posts whether the meta was empty or not?

So instead I looked to see if the field contained a double quote:

    'key' => 'field_name',
    'value' => '"',
    'compare' => 'LIKE'

As ACF uses double quotes in an array structure for multi selects stored in the DB.

Hope this helps someone who has fallen into the same trap as I :-)

-4
!has_featured_image();

one liner ftw.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.