1

I have an array to store taxonomy and term for query, but I can not use foreach to loop my array inside my tax_query. I got 505 internal.

    $query = array(
        'post_type' => $post_type,
        'posts_per_page' => -1,
    );

    $query['tax_query'] = array(
         'relation' => 'OR',

        foreach($taxonomy_arr as $t):
            array(
                'taxonomy' => $t[taxonomy],
                'terms' => $t[value],
                'field' => 'slug',
            ),
        endforeach;
    );

the foreach or the query works fine on its own but does not work when I loop inside. Please give me advice. Thanks

1 Answer 1

3

This is a PHP syntax error - you can't nest a foreach inside an array, you use it to build the array:

$query = [
    'post_type'      => $post_type,
    'posts_per_page' => -1,
    'tax_query'      => [
        'relation' => 'OR',
    ],
];

foreach ( $taxonomy_arr as $t ) {
    $query['tax_query'][] = [
        'taxonomy' => $t['taxonomy'],
        'terms'    => $t['value'],
        'field'    => 'slug',
    ];
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.