1

I'm trying to use custom fields on the backend to set the taxonomies in a WP_Query for a category archive on the front end.

In the page template. this gets my categories from the custom field:

$terms = get_field('add_categories_custom_template', $term->term_id);

if( $terms ):
foreach( $terms as $term ): 

echo $term; echo ',';

endforeach; 
endif; 

That gives me an output like this:

12,345,900,

But how do I get that output into the 'terms' => array for the tax_query? What I need is the array of IDs to be output this way:

'tax_query' => array(
        array(
            'taxonomy'  => 'product_cat',
            'field'     => 'term_id',
            'terms'     => array('12,345,900'),  // output this way
            'operator'  => 'IN',
        )
   )

But doing this

$terms = get_field('add_categories_custom_template', $term->term_id);

if( $terms ):
foreach( $terms as $term ): 

$my_terms = $term; echo ',';

endforeach; 
endif; 

and this

'tax_query' => array(
        array(
            'taxonomy'  => 'product_cat',
            'field'     => 'term_id',
            'terms' => array($my_terms),
            'operator'  => 'IN',
        )
   )

only outputs the first $term (i.e., 12) and not the subsequent terms (345 and 900).

1
  • note that this isn't a custom field, it's an ACF field accessed via an ACF API, 3rd party plugin dev support for ACF is off topic here
    – Tom J Nowell
    Nov 15 '21 at 18:51
1

if you need to turn it into an array of IDs then it is already an array of IDs, you don't need to do any work on it, it's already in the perfect form to go straight into the terms parameter

e.g.

    'terms' => $terms,

The only thing to be mindful about though, is that get_field is not a WordPress function, it's an ACF function, and you will need to handle the situation where this field has no value or an error occurs. You will need to ask how to handle that in an ACF community or via their support as ACF fields are off topic here.

1
  • Thanks! That works; I didn't need array($terms). And you're right, I am using ACF and should check for the existence of the field and if it is not empty. Nov 15 '21 at 21:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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