Home Forums General Issues WP_Query if field is populated


WP_Query if field is populated

  • Hi, I’ve read the documentation entry about “How to query posts filtered by custom field values” (, which is close to what I’m trying to do, but not quite there.

    Using wp_query, I need to show one of several custom post types (type=portfolio), ordered randomly but only if a certain custom field (client_quote) is populated.

    Right now I’ve got this code:

    $recentPosts = new WP_Query();

    But obviously that shows every portfolio post regardless of whether the “client_quote” field is populated or not.

    Any pointers?

  • Solved it. For anyone else wondering, this is how I did it:

    $args = array(
    	'numberposts' => -1,
    	'post_type' => 'portfolio',
    	'showposts' => 1,
    	'orderby' => 'rand',
    	'meta_query' => array(
    		'relation' => 'AND',
    			'key'     => 'client_quote',
    			'value'   => '',
    			'compare' => '!='
    $client_quote = new WP_Query( $args );

    That randomly picks one post from the Portfolio custom post type, as long as the client_quote custom field contains some text.

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘WP_Query if field is populated’ is closed to new replies.