Only show parent term from custom taxonomy

Hello,

How can I only show the top-level taxonomies when using a query loop to show posts?

So for example I have a custom post type called ‘stores’ and a custom taxonomy called ‘store category’
The store category example is built up like this:

  • DIY
    (-construction, -home, -etc)
  • Fashion
  • Outdoor
    (-climbing, running, hiking)

I have made query to show all the stores with name, location, etcetera. But I also want to show the ‘store category’ per “post” but only the main level. So only DIY, Fashion or Outdoor should been shown.

I think I need another query loop within the queryloop, but then? I can’t really figure it out yet.

Thanks for the help!

2 Likes

Maybe this can help:
image

1 Like

I have looked at that functionality and It would definitely help on the short term. But it can quickly become a big maintenance as more taxonomy categories get added. So I hope there is a more scalable solution available.

If I understand you correctly, you were trying to output the top level category for each loop right?

You should create a custom php function and use a basic text element to echo out.

Example:

function itchy_prod_first_level_categories() {
  global $product;
  if($product) {
	//Get the current product category
    $terms = get_the_terms( $product->get_id(), 'product_cat' );

    $cats = [];
	
	//Loop the terms and only save terms parent id is 0
    foreach( $terms as $term ) {
		if ($term->parent > 0) continue;
		$cats[] = $term->name;
    }
	
	//Return the first parent term only
    return (count($cats) > 0) ? $cats[0] : '';
  }
}

And I output this in my product loop template

4 Likes

Hi, yes of a custom taxonomy.
So I’ll have to tweak your code a bit. Will definitely try it.

sure, just change product_cat to your custom taxonomy

You can do this with the default Bricks query loop by setting the parent value to 0.

You probably fixed this by now, but for future visitors - you can do this with no code - on any page.
The ‘parent 0’ trick only works for main categories - if you go to a subcat, it breaks (because these have parents).
You can get ONLY the NEXT CHILD Categories by putting {echo:get_queried_object_id}
In both PARENT and CHILD OF - in the query.
In a category archive, this returns just same-level categories, enabling you to ‘walk down’ the category tree and show ‘next branches’ to go down - with a single template.

So on you store it would show DIY, FASHION, OUTDOOR
Go to OUTDOOR - and the same archive template shows climbing, running, hiking

If you had Hiking->boots, trousers, gear
Then on Hiking page it would show those… ad infinitum.