Auto-tag orders with product vendors, with Mechanic.

Mechanic is a development platform for Shopify. :)

Auto-tag orders with product vendors

by Isaac Bowen (team@usemechanic.com)

Use this task to automatically tag incoming orders with the vendor of each product in the order.

Runs when an order is created.

15-day free trial – unlimited tasks

Documentation

Use this task to automatically tag incoming orders with the vendor of each product in the order.

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)
Script
{% if event.preview %}
  {% capture order_json %}
    {
      "admin_graphql_api_id": "gid://shopify/Order/12345",
      "tags": "Apple",
      "line_items": [
        {
          "product": {
            "vendor": "Apple"
          }
        },
        {
          "product": {
            "vendor": "Nike"
          }
        },
        {
          "product": {
            "vendor": null
          }
        }
      ]
    }
  {% endcapture %}

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

{% assign product_vendors = order.line_items | map: "product" | map: "vendor" %}
{% assign order_tags = order.tags | split: ", " %}
{% assign tags_to_add = array %}

{% for vendor in product_vendors %}
  {% if vendor == blank or order_tags contains vendor %}
    {% continue %}
  {% endif %}

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

{% if tags_to_add != blank %}
  {% action "shopify" %}
    mutation {
      tagsAdd(
        id: {{ order.admin_graphql_api_id | json }}
        tags: {{ tags_to_add | json }}
      ) {
        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.