I am seeking help on a specific value using a custom variable.
My objective is to populate a single text line metafield with a segment of any of the skus in the variants.
In my current setup, I have the following line:
{{ product.variants | map: "sku"}}
returning a string of all the SKUs of every variant. This code returns the entire SKU string, for example:
AB1234-56Z-7890-XY-CD1234-56Z-7890-XY. However, I am looking to modify this code so that it only returns the first two segments of the entire string, like: AB1234-56Z.
Is there a way to adjust the variable to achieve this truncation?
It makes sense, but when I try to put any sort of variant I get an error saying it’s invalid.
Not just if I wanna pull a SKU, even if I put product.title it says it’s invalid:
Thanks for raising this. There seems to be a bug in how the variables are being validated after splitting which we’ll need to look into. I’ve logged it and will raise it with the team on Monday.
As a workaround for now, you can iterate through the array after splitting instead, which will pass validation.
{% for variant in product.variants %}
{% assign sku = variant.sku %}
{% assign parts = sku | split: '-' %}
{% assign first_two_parts = "" %}
{% for part in parts %}
{% if forloop.index <= 2 %}
{% assign first_two_parts = first_two_parts | append: part | append: '-' %}
{% else %}
{% break %}
{% endif %}
{% endfor %}
{% assign first_two_parts = first_two_parts | remove: '-' | append: '-' %}
{{ first_two_parts }}
{% endfor %}