Auto-tag orders with product tags, with Mechanic.

Mechanic is a development and ecommerce automation platform for Shopify. :)

Auto-tag orders with product tags

This task watches for new orders, and copies tags from each ordered product to the order itself.

Runs Occurs whenever an order is created. Configuration includes only copy these product tags.

15-day free trial – unlimited tasks

Developer details

Mechanic is designed to benefit everybody: merchants, customers, developers, agencies, Shopifolks, 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.

(By the way, have you seen our documentation? Have you joined the Slack community?)

Open source
View on GitHub to contribute to this task
Subscriptions
shopify/orders/create
Tasks use subscriptions to sign up for specific kinds of events. Learn more
Options
only copy these product tags (array)
Code
{% if event.preview %}
  {% capture order_json %}
    {
      "admin_graphql_api_id": "gid://shopify/Order/1234567890",
      "tags": "",
      "line_items": [
        {
          "product": {
            "tags": {% if options.only_copy_these_product_tags__array %}{{ options.only_copy_these_product_tags__array | join: ", " | json }}{% else %}"a, b, c"{% endif %}
          }
        }
      ]
    }
  {% endcapture %}

  {% assign order = order_json | parse_json %}
{% endif %}

{% assign tags_to_add = array %}
{% assign order_tags = order.tags | split: ", " %}

{% for line_item in order.line_items %}
  {% assign product_tags = line_item.product.tags | split: ", " %}
  {% for tag in product_tags %}
    {% if order_tags contains tag %}
      {% log message: "Order already has this product tag", tag: tag %}
      {% continue %}
    {% endif %}

    {% if options.only_copy_these_product_tags__array != blank %}
      {% unless options.only_copy_these_product_tags__array contains tag %}
        {% log message: "This product tag is not in the whitelist", tag: tag %}
        {% continue %}
      {% endunless %}
    {% endif %}

    {% assign tags_to_add[tags_to_add.size] = tag %}
  {% endfor %}
{% endfor %}

{% if tags_to_add != empty %}
  {% action "shopify" %}
    mutation {
      tagsAdd(
        id: {{ order.admin_graphql_api_id | json }}
        tags: {{ tags_to_add | json }}
      ) {
        node {
          ... on Order {
            id
            name
            tags
          }
        }
        userErrors {
          field
          message
        }
      }
    }
  {% endaction %}
{% endif %}
Task code is written in Mechanic Liquid, an extension of open-source Liquid enhanced for automation. Learn more