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

All we need is an easy explanation of the problem, so here it is.

How do I query_posts and only show results if a custom field is not empty or has a value.

I want to put in a URL in a custom field and only show these pages if there is a URL?

current code but I can’t figure out the rest:

$args = array( 'posts_per_page' => '10', 
    'post_type' => 'programmes', 
    'orderby' => 'meta_value_num', 'meta_key' => 'popularityfig',
    'order'  => 'DESC',

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Try this code:

$args = array(
'posts_per_page' => '10',
'post_type' => 'programmes',
'meta_key' => 'popularityfig',
'meta_value' => '',
'meta_compare' => '!=',
'order' => 'DESC'

There’re 2 arguments you might want to note in the code: meta_value and meta_compare. Using meta_compare with operator != will exclude posts with empty meta value.

Method 2

It’s not clear if the answer above actually worked for you @erichmond, but it definitely did not for me. Found a solution though. See: How can I show posts only if meta_value is not empty

Method 3

The accepted answer was not working for me with a text field in Advanced Custom Fields. It kept pulling all posts once they were saved after the text field was added to the Custom Fields. I had to do a similar solution to others:

$args = array(  
    'meta_key' => 'your_acf_field',
    'meta_value' => array(''),
    'meta_compare' => 'NOT IN',

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply