af3000
af3000

Reputation: 1

Shopify - Capturing a Metafield Value of the Last Added Collection with a Custom Template

I'm working on a theme where I've got several collections of clothing and I have created a custom collection template called 'seasonal', with the intent of using a custom background color for that specific type of collection.

I've achieved this by using metafields. It's working fine and I now have two seasonal collection pages - FW15 and SS16, with two different background colors,

I would now like to fetch the background color of the most recent 'seasonal' collection in another page of the theme.

This is where I'm stuck in. See the code below:

{% for collection in collections reversed %}
{% if collection.template_suffix contains 'seasonal' %}
{% assign seasonalCollectionColor = collection.metafields.c_f.Collection_Color | split: "|" %}
{{ seasonalCollectionColor[0] }}
{% endif %}
{% endear %}

This is outputting both seasonal collection colors:

#8DE5EB #FF7C1A

Instead of just the most recent one, which I'm trying to get by appending [0] to seasonalCollectionColor.

Any help on what am I doing wrong?

Thanks in advance!

Upvotes: 0

Views: 227

Answers (1)

David Lazar
David Lazar

Reputation: 11427

You are in a loop. The loop has one condition you are triggering off of (contains seasonal). Hence you capture the result twice, and output it twice. You are not limiting your test to the condition of most recent.

If you were to try and test for the condition of most recent, what would that be? In your case, perhaps since you are traversing collections in a reverse order, the first occurrence is your most recent one.

So add a condition that if the condition is found, and you have set the seasonalCollectionColor to something, DO NOT set it again... just ignore any other values that match, and then you'll have only one value, the most recent one.

Upvotes: 0

Related Questions