Our requirement is that in the New Arrivals collection, which contains a total of 7000+ products, the New Test tag should be removed from the newest 150 products, and the tag should be added to the remaining products. This flow should be triggered whenever I update the products in this collection.
Code
{% if event.topic == "shopify/collections/update" and collection.handle == "new-arrivals" %}
{% assign tag = "New Test" %}
{% assign latest_without_tag = 150 %}
{% assign products = shop.collections["new-arrivals"].products | sort: "created_at" | reverse %}
{% for product in products %}
{% assign index = forloop.index0 %}
{% if index < latest_without_tag %}
{% comment %}Latest 150 → tag remove{% endcomment %}
{% if product.tags contains tag %}
{% action "shopify" %}
mutation {
tagsRemove(
id: {{ product.admin_graphql_api_id | json }},
tags: ["New Test"]
) {
userErrors { field message }
}
}
{% endaction %}
{% endif %}
{% else %}
{% comment %}Rest all → tag add{% endcomment %}
{% unless product.tags contains tag %}
{% action "shopify" %}
mutation {
tagsAdd(
id: {{ product.admin_graphql_api_id | json }},
tags: ["New Test"]
) {
userErrors { field message }
}
}
{% endaction %}
{% endunless %}
{% endif %}
{% endfor %}
{% log "New Test tag updated – Latest {{ latest_without_tag }} without tag, rest with tag | Total: {{ products.size }} products" %}
{% endif %}