Auto-tag orders by product collections with Mechanic.

Mechanic is the one-tool-does-it-all automation app for Shopify. :)

Auto-tag orders by product collections

by Isaac Bowen (team@usemechanic.com)

Use this task to automatically tag orders based on what collection(s) the customer has ordered from. Useful for broadly classifying orders according to their contents.

Runs when an order is created. Configuration includes collections and tags.

15-day free trial – unlimited tasks

Documentation

Fill in the "Collections and tags" option with the collection on the left, and tags on the right. When specifying the collection, you can use the collection title (e.g. "Summer Swimware"), handle ("e.g. summer-swimware"), or ID (e.g. 27359487103). These are all case-sensitive, so double-check your work!

Developer details

Mechanic is designed to benefit everybody: merchants, customers, developers, agencies, Gurus, everybody.

That’s why we make it easy to configure automation without code, why we make it easy to tweak the underlying code once tasks are installed, and why we publish it all here for everyone to learn from.

Events
when an order is created (shopify/orders/create)
Options
collections and tags (keyval, required)
Script
{% assign tags_to_save = order.tags %}

{% unless event.preview %}
  {% assign order_collections = nil %}
  {% for line_item in order.line_items %}
    {% assign order_collections = order_collections | concat: line_item.product.collections %}
  {% endfor %}
  {% assign order_collection_ids = order_collections | map: "id" | join: "," | split: "," %}
  {% assign order_collection_titles = order_collections | map: "title" %}
  {% assign order_collection_handles = order_collections | map: "handle" %}
{% endunless %}

{% for pair in options.collections_and_tags__keyval_required %}
  {% assign required_collection = pair[0] %}
  {% assign tag = pair[1] %}

  {% if order_collection_ids contains required_collection
        or order_collection_titles contains required_collection
        or order_collection_handles contains required_collection
        or event.preview
  %}
    {% assign tags_to_save = tags_to_save | add_tag: tag %}
  {% endif %}
{% endfor %}

{% if event.preview or tags_to_save != order.tags %}
  {
    "action": {
      "type": "shopify",
      "options": [
        "update",
        [
          "order",
          {{ order.id | json }}
        ],
        {
          "tags": {{ tags_to_save | json }}
        }
      ]
    }
  }
{% endif %}
Mechanic tasks are written in Liquid, which makes them easy to write and easy to modify. Learn more about our platform.
Defaults
Collections and tags
{"Summer Swimware"=>"summer, swimware", "Cold Weather Gear"=>"winter"}