Query loop to output list of terms which are set from an acf taxonomy field

Been pulling my hair out over this one and just can’t figure it out.

I have an acf taxonomy field in which I can select multiple terms. Currently, the only way I found to output these terms is by adding a code block, following the acf docs like so:

<?php 
$terms = get_field('taxonomy_field_name');
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; ?>

This works but I’m wondering if there is a way to output them using a query loop.

The reason I wanna use a query loop is that my cpt can be assigned (relationship field) another cpt and also one or more of these terms. Ultimately I’d have one wrapper in which I’ll have 2 queries, one for the assigned cpts and one for the assigned terms. Just makes it easier to style and manage.

Any ideas?:slight_smile:

Would need to know where the terms are actually being saved…

  1. Are you using a Options Page for controlling these terms?
  2. Are these terms being saved directly to the CPTs themselves… or the post type’s meta?

Aside from above, you can actually do away with that code block and just use brick’s type dropdown for the query! Meaning you can have ANY simple or complex query, give it a name and then select it right in bricks query type dropdown…

Terms are being saved in 2 places

  1. An options page to decide which ones to show on the homepage
  2. The cpts themselves to show and link the selected terms on the cpt Single template

So ultimately I gotta figure out both haha but I guess if I get one of em, the other shouldn’t be too hard.

I’ve seen that post and tried to create my own queries. Where I’m stumped though, or simply too stupid for, is creating a query that will get and output the terms.
Most threads on stackoverflow and other sites show queries that filter posts by a taxonomy and then show the posts, not the taxonomy terms themselves.

On the single cpt template I kinda got it working by creating a query that gets all the terms of my taxonomy, and then a conditional display set up like so, to only show the ones that were actually assigned to that cpt within the acf taxonomy field:

image

What I found weird though is that it only works when checking for the term_name, not id or anything else. When I use the ID, it matches some correctly but throws in another random one as well sometimes. Furthermore, this hacky workaround using conditions doesn’t work on the homepage where I’m getting the terms from an options page.

My brain is on fire with this haha

Also in reference to ACF relational:

Funny I was just about to say create a really simple template to display them… save and then use the template in your query loop output… and your post magically refreshed with your template lol.

Yea, term_name I would never use, infact term_name is optional anyways… not even required.
I would query by post type slug first… and then term id. BUT, make sure in ACF you have return format set to ID!

And you may be getting that one off term because you are using “contains” instead of “is”?

Ha, saw that vid about an hour ago :smiley:

It also focuses on posts though, not the terms themselves. The “traditional” relationship field for posts works fine, the taxonomy field (ACF | Taxonomy) however is the one giving me headaches.

I’ll try “is” and see if I can match by ID which is more reliable anyway.

Still would love to somehow get this to work within a query and not with conditional displays, since that trick doesn’t work when the taxonomy field is on an options page.

At this point I don’t even know what to google for anymore haha might have to take a day or two away from this.

Here is my setup with the options page, might make it clearer:

ACF Taxonomy field:

Query which doesn’t return anything since (I’m guessing) my attempts at the meta query are all over the place:

wait… for meta query you have start_xxxxxx
isn’t start the beginning of an accordian or group? Is that the correct meta key?

And you dont have any “include terms” set

you mean prepend an underscore to the field name?
Not an accordion or anything, just regular good old div.

as for no “included terms” set, tried adding all terms but doesn’t make a difference. I mean I could just set it up in there and remove the meta query but my goal is to be able to set it from the options page hehe. Probably overcomplicating things.

Managed to get the correctly assigned IDs by using the following function:

function by_the_category() {
	$the_data = get_field('start_rechtsgebiet_katgeorien', 'options');
	$a = implode(',', $the_data);
	return $the_data;
}

tried to use it it like so:
image
But of course doesn’t work haha

Just outputting it in the frontend gives me

string(11) "21,26,17,22"

Correct IDs but no idea how to properly use it from here

1 Like

for the ACF meta key… it starts with “start_xxx”
that looks like the start of an accordion for your field groups… when editing on editing screen for the post.

Oh haha, nah that’s just the field name I gave since the homepage is the “startseite” in german :wink:

ok, you have the string of IDs…
So try to echo them with some simple HTML…

I did a var dump which then shows them in the frontend, just can’t seem to figure out how to get them into the query to check against them.

Might just opt for doing the whole thing in a codeblock but I’m stubborn and wanna figure it out using a query haha

lol… you have me wanting to try this on one of my installs of ACF, except I dont use ACF for terms, probably never would!
Your issue wouldn’t even be an issue using wp core taxanomy lol

hehehe go for it :stuck_out_tongue:

thing is I’m using the core taxonomies for the blog so I used acf (switched from cpt ui) to create my cpts and taxonomies. Easy to loop over the terms and output them in a codeblock, just not getting them from a regular WP Query. Just ain’t got enough PHP skills for this haha, wish I could build everything in react lol

With ACF… these are a must for me…

Actually got acf extended installed, to make my other relationship fields bidirectional. Checked their docs as well and see if it would work with their “Taxonomy Terms” field, same issues though.

Getting closer, kinda figured out the WP_Term_Query. It works and returns the correct stuff when I use it in a codeblock in my single cpt template:"

<?php
$custom_terms = get_field('rechtsgebiet_kats');
//var_dump($custom_terms);
$args = array(
    'taxonomy'               => 'rechtsgebiet-kategor',
    'orderby'                => 'name',
    'order'                  => 'ASC',
    'hide_empty'             => false,
  	'include'               => $custom_terms,
);

$the_query = new WP_Term_Query($args);
foreach ($the_query->get_terms() as $term) { ?>
    <?php echo $term->name; ?>

<?php } ?>

Next challenge is to implement this into a custom query as per Adding any Custom WP_Query loop to Bricks' Query Loop - BricksLabs
Just copying over the args n stuff didn’t work of course, would’ve been too easy haha

EDIT: seem to have figured it out. Here is the complete code to add the query (only last function is the one actually doing the work):

/* Add new query type control to query options */
add_filter( 'bricks/setup/control_options', 'bl_setup_query_controls');
function bl_setup_query_controls( $control_options ) {

    /* Adding a new option in the dropdown */
    $control_options['queryTypes']['anwaelte_recht_cats'] = esc_html__( 'My new WP Query' );

    return $control_options;

};

/* Run new query if option selected */
add_filter( 'bricks/query/run', 'bl_maybe_run_new_query', 10, 2);
function bl_maybe_run_new_query( $results, $query_obj ) {
	
    if ( $query_obj->object_type !== 'anwaelte_recht_cats' ) {
	    return $results;
    }
    
    /* If option is selected, run our new query */ 
    if ( $query_obj->object_type === 'anwaelte_recht_cats' ) {
        $results = run_new_query();
    }
    
    return $results;

};


/* Setup post data for posts */
add_filter( 'bricks/query/loop_object', 'bl_setup_post_data', 10, 3);
function bl_setup_post_data( $loop_object, $loop_key, $query_obj ) {
    
    if ( $query_obj->object_type !== 'anwaelte_recht_cats' ) {
	    return $loop_object;
    }

     global $post;
     $post = get_post( $loop_object );
     setup_postdata( $post );
    
     return $loop_object;

};


/* Return results from our custom WP Query arguments */
function run_new_query() {
$custom_terms = get_field('rechtsgebiet_kats');
    /* Add all of your WP_Query arguments here */
var_dump($custom_terms);
$args = array(
    'taxonomy'               => 'rechtsgebiet-kategor',
    'orderby'                => 'name',
    'order'                  => 'ASC',
    'hide_empty'             => false,
  	'include'               => $custom_terms,
);
    
    $term_query = new WP_Term_Query( $args );
    if ($custom_terms) {
    return $term_query->terms;
    }
    

};

It just dawned on me… When you are doing your query loop in bricks… and you have the loop query on the container… THEN why not just add a Basic Text, and then use the Dynamic Data bolt… then select your acf terms?
When I do that EVERY thing ACF has comes up for me! Here I have loop on container… dropped in Basic Text Element, dynamic data… ALL ACF STUFF available… you should see your taxo

screenshot-2023.06.01-01_54_42

screenshot-2023.06.01-01_54_40

That works, the thing in my case is that I have a weird combination of taxonomy terms and posts I wanna display. Got it all working on my cpt single template but still struggling on the homepage.

I think I may have poorly explained haha. Getting stuff from a taxonomy or getting posts is easy peasy with the regular query. I’ll try to be clearer using the homepage as an example.

For the homepage I have two fields on an options page.

  1. ACF Taxonomy field in which I can select multiple existing terms
  2. ACF Relationship field in which I can select multiple posts

All the posts from 2. are part of one of the terms of 1.

The goal rn is to be able to go to the options page, select a few taxonomy terms as well as a few posts.
In the frontend, I loop over the selected taxonomies like so:

    $custom_terms = get_field('start_rechtsgebiet_katgeorien', 'option');
    /* Add all of your WP_Query arguments here */
//var_dump($custom_terms);
$args = array(
    'taxonomy'               => 'rechtsgebiet-kategor',
    'orderby'                => 'name',
    'order'                  => 'ASC',
    'hide_empty'             => false,
  	'include'               => $custom_terms,
);
    
    $home_term_query = new WP_Term_Query( $args );
    
    if ($custom_terms) {
    return $home_term_query->terms;
    }

Within this loop, under each taxonomy term, I wanna list the posts that were selected in the relationship field. So far so good except that if I go for a regular relationship query, it shows all the selected posts under each taxonomy term. I want each selected post to only show under the taxonomy term it actually has assigned.

Right now, the furthest I’ve gotten is showing them under the right taxonomy terms but then it ignores the relationship field.

It’s starting to mess with my brain and it’s kinda very specific and hard to illustrate, so I’ll likely do a complete write up once I figured it out haha. Appreciate all the help though! :slight_smile:

Sometimes it’s hard for me to remember what is capable just in core ACF, as I have Extended installed too.
So, I’m not even sure IF core has the frontened / backend display options and settings (Extended adds all of that functionality). I say this because I’m assuming that you DO HAVE these terms / fields set to display on the frontend? I would assume so if your CPT single template is in fact working on frontend (not just in builder). Sometimes we overlook the smallest things thinking the issue is with the ‘code’.

Is it possible to just drop the ACF Relation, and just use a single term OR add a custom field JUST to create a “relation” between posts? That would eliminate your dependency on ACF + it’s taxo + relations + ACF meta keys while trying to do this query. The query would be MUCH MUCH easier with a WP core term or custom field!

At this point, I’m confused lol… I see your include, which is everything… but you said

but then you have no exclude? Is this the only function you’re using? confused

I think I’ve confused myself with this one haha. In the end, at least for the homepage I opted for a workaround but I’ll be drawing up a lil diagram on Monday for myself anyway and then I’ll post it here together with how I did each step. At that point it should be clearer.

Pretty sure I was trying to make wp do things it just doesn’t like to do but those are the fun things to tinker with anyway :smiley: