• Resolved Martin

    (@martinlucas)


    I have a wp_query that grabs a custom field, this custom field is a term id for a category of a custom post type’s categories called classes. If only one type is selected then this code works fine;

    <?php $listing_cat = get_post_meta(get_the_ID(), 'show_what_listings', true);
    $listing_cat_commad = implode(", ", $listing_cat); ?>
    
    <?php
    $args = array(
    	'orderby' => 'meta_value',
    	'meta_key' => 'listing_date',
    	'order' => 'ASC',
    	'post_type' => 'events',
    	'posts_per_page' => -1,
    	'tax_query' => array(
    		array(
    			'taxonomy' => 'classes',
    			'field' => 'id',
    			'terms' => array( $listing_cat_commad )
    		)
    	)
    );
    
    $the_query = new WP_Query( $args );
    
    and so on

    if there is multiple term id’s selected then it doesn’t work. I have echo’d the variable and that looks fine – ie 4, 7, 8 – and if I just replace the variable with 4, 7, 8 in the terms => array then it works.

    Any help would be much appreciated?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter Martin

    (@martinlucas)

    I forgot to mention, when multiple terms are selected within the custom field and the array is populated via the variable with something like 4, 7, 8 it only shows the posts from the first category – in this case id 4.

    Moderator keesiemeijer

    (@keesiemeijer)

    If the meta value for ‘show_what_listings’ is a string (‘4, 7, 8’) you need to make it an array

    $listing_cat_commad = explode(", ", $listing_cat);

    and query like so in your tax_query:

    'terms' => $listing_cat_commad

    Set $single to false if you used the meta key multiple times and want to return an array with all the values:

    $listing_cat = get_post_meta(get_the_ID(), 'show_what_listings', false );
    if(!empty($listing_cat)) {
    // do stuff for $listing_cat;
    }

    And you don’t need to use implode because the ‘terms’ parameter accepts arrays.

    https://codex.www.ads-software.com/Function_Reference/get_post_meta

    Thread Starter Martin

    (@martinlucas)

    Thanks, that’s great – it works. I didn’t need to explode it back into an array as I was already getting the array into a variable with this line;

    $listing_cat = get_post_meta(get_the_ID(), 'show_what_listings', true);

    so just used $listing_cat variable.

    Much appreciated!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘WP_Query, using a variable in tax_query terms’ is closed to new replies.