Auto-tag orders with product tags, with Mechanic.

Mechanic is a development platform for Shopify. :)

Auto-tag orders with product tags

by Isaac Bowen (team@usemechanic.com)

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

Runs when 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, 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
only copy these product tags (array)
Script
{% 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 %}
Mechanic tasks are written in Liquid, which makes them easy to write and easy to modify. Learn more about our platform.