[resolved] WP_Query, using a variable in tax_query terms (4 posts)

  1. Martin
    Posted 3 years ago #

    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); ?>
    $args = array(
    	'orderby' => 'meta_value',
    	'meta_key' => 'listing_date',
    	'order' => 'ASC',
    	'post_type' => 'events',
    	'posts_per_page' => -1,
    	'tax_query' => 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?

  2. Martin
    Posted 3 years ago #

    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.

  3. keesiemeijer
    Posted 3 years ago #

    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.


  4. Martin
    Posted 3 years ago #

    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!

Topic Closed

This topic has been closed to new replies.

About this Topic