Simplifying Code with multiple taxonomies

I have a loop to display products. It checks if there is a url query “product_cat” and displays different loops if it exists. I think there must be a simpler way of writing it but I can’t figure it out. Here’s a simplified version of my code:

<Loop field=archive_term>
  <Set term_id><Field id /></Set>
  <Set taxonomy_id><Field taxonomy /></Set>
</Loop>

<If check="{Url query=product_cat}" exists>
  <Loop type="product" taxonomy="{Get taxonomy_id /}" terms="{Get term_id /}" taxonomy_2="product_cat" terms_2="{Url query=product_cat /}">
    <Field title />
  </Loop>
<Else />
  <Loop type="product" taxonomy="{Get taxonomy_id /}" terms="{Get term_id /}">
    <Field title />
  </Loop>
</If>

I have a whole lot of other stuff in there other than just title and it would be much easier to maintain if I didn’t have to have 2 loops.

Hi Paul,

I’ve run into this problem before, but I could not find a way of conditionally changing the parameters of the Loop field. It’s best to implement a solution that avoids this scenario.

One way to resolve this is to make your URL structure consistent and use a product_cat value of ‘default’ or ‘all’ when it’s not applicable.

1 Like

Hi Paul, I forgot there is another way to make it easier to manage repeated code.

If the logic inside your loops is the same, you can move it to another template and call it using the <Template> tag.

Example calling a template called post-item:

<If check="{Url query=product_cat}" exists>
  <Loop type="product" taxonomy="{Get taxonomy_id /}" terms="{Get term_id /}" taxonomy_2="product_cat" terms_2="{Url query=product_cat /}">
    <Template name="post-item" />
  </Loop>
<Else />
  <Loop type="product" taxonomy="{Get taxonomy_id /}" terms="{Get term_id /}">
    <Template name="post-item" />
  </Loop>
</If>