Support

Account

Home Forums General Issues WP_Query if field is populated

Solved

WP_Query if field is populated

  • Hi, I’ve read the documentation entry about “How to query posts filtered by custom field values” (http://www.advancedcustomfields.com/resources/how-to/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:

    <?php
    $recentPosts = new WP_Query();
    $recentPosts->query('showposts=1&post_type=portfolio&orderby=rand');
    ?>

    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:

    <?php 
    $args = array(
    	'numberposts' => -1,
    	'post_type' => 'portfolio',
    	'showposts' => 1,
    	'orderby' => 'rand',
    	'meta_query' => array(
    		'relation' => 'AND',
    		array(
    			'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)

You must be logged in to reply to this topic.