Excluding empty meta_key values in WP_Query results

Mere Development picture Mere Development · May 10, 2012 · Viewed 10.5k times · Source

I'm using WP_Query to pull out some custom posts like this:

$params = array(            
        'post_type' => 'portfolio',
        'post_status' => 'publish',
        'posts_per_page' => 10,
        'meta_key' => 'slideorder',
        'orderby' => 'meta_value',
        'order' => 'ASC'
        'ignore_sticky_posts' => 1,
    );
$slport_query = new WP_Query($params);

The problem I'm facing is that even if the 'slideorder' (string) is empty, it's being included in the result. How would I only retrieve posts where 'meta_value' has at least one char in it?

I've tried to add:

'meta_value' => '',
'meta_compare' => '!=',

but that's not helped. Any ideas?

Thanks, Ben

Answer

Mere Development picture Mere Development · May 10, 2012

Ok... Here's the solution. It seems that even apparently empty meta_values have or return a single space. So this works:

$params = array(
    'post_type' => 'portfolio',
    'post_status' => 'publish',
    'posts_per_page' => 10,
    'meta_key' => 'slideorder',
    'meta_value' => ' ',
    'meta_compare' => '!=',
    'ignore_sticky_posts' => 1,
    'orderby' => 'meta_value',
    'order' => 'ASC'
);
$slport_query = new WP_Query($params);