ccmanz
ccmanz

Reputation: 181

How to query terms with array variable?

So I have this code here, been trying different ways but it will only load the last iteration of $taxterm for 'terms' => $taxterm. Any thoughts why its doing this?

foreach($term_tags as $term) {

    $taxterm = array();
    $taxterm[] = $term->slug;   

    }

        $args = array(
                'post_type' => 'cp_recipe',
                'orderby' => 'title',
            'order'   => 'ASC',
                'tax_query' => array(
                         array(
                                'taxonomy' => 'cp_recipe_tags',
                                'field' => 'slug',
                                'terms' => $taxterm
                                  ),
                            ),
                 );

Thanks, Carl

Upvotes: 0

Views: 49

Answers (1)

Aydin4ik
Aydin4ik

Reputation: 1935

Take the $taxterm = array(); line outside the foreach loop, like so:

$taxterm = array();
foreach($term_tags as $term) {
    $taxterm[] = $term->slug;   

}

When the array is declared within the foreach loop, it is re-declared on every iteration, ie, is reset to a blank array each time. When declared outside, it is not reset but gets populated with each iteration.

You can read more about variable scoping in PHP here: http://php.net/manual/en/language.variables.scope.php

Upvotes: 1

Related Questions