I am using an ACF Taxonomy field (not a custom taxonomy) that allows the user to select categories from a checkbox list. On the page, I want to loop through each of the selected categories, creating a list of links to each cat archive.
Is there a way to do this with the Query Loop? The ACF Taxonomy field does not show up in the “Type” drop-down the way a Repeater or Relationship field does. I’ve tried to use meta queries, but I don’t have my head wrapped around them well enough to know what I’m doing.
For reference, documentation on the ACF Taxonomy field: https://www.advancedcustomfields.com/resources/taxonomy/
A little more information. When I create a code block and use the code below directly from the ACF support page (but with an added var_dump
), the field acf_my_taxonomy_field
returns null.
<?php
$terms = get_field('acf_my_taxonomy_field');
echo var_dump($terms); //Added by me, returns NULL
if( $terms ): ?>
<ul>
<?php foreach( $terms as $term ): ?>
<li>
<h2><?php echo esc_html( $term->name ); ?></h2>
<p><?php echo esc_html( $term->description ); ?></p>
<a href="<?php echo esc_url( get_term_link( $term ) ); ?>">View all '<?php echo esc_html( $term->name ); ?>' posts</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
However, if I use the dynamic tag {acf_my_taxonomy_field}
somewhere else on the page, like in a Basic Text element, it works great and outputs a list of the categories with cat archive links. I can also add :value
and it lists the cat ids.
Why can’t I access this custom field via PHP?
Ah! I got it to work. This is the code I ended up using for the query, in case anyone else finds this thread and needs it:
$custom_terms = get_field('my_taxonomy_field'); // Access ACF Taxonomy
$custom_terms_string = implode(',', $custom_terms); // Convert to comma separated list
return [
'taxonomy' => 'category',
'orderby' => 'name',
'order' => 'ASC',
'include' => $custom_terms_string,
];
So what went wrong before? I’m not positive, but here’s what I found:
- I should not have been adding “acf_” to the front of my custom field name in the query editor. Removing that fixed the NULL issue. HOWEVER…
- I got some kind of PHP error related to converting strings. Apologies, I’ve lost track of what the exact error was—but this was my cue to convert the field to a plain list of comma separated ids.