Auto-tag customers when they purchase a matching product with Mechanic.

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

Auto-tag customers when they purchase a matching product

by Isaac Bowen (team@usemechanic.com)

Configure this task with a product title and/or tag to watch for, and this task will apply the tag of your choice to every customer who makes a matching purchase.

Runs when an order is paid. Configuration includes customer tag to apply, required product tag, and required product title.

15-day free trial – unlimited tasks

Developer details

Events
when an order is paid (shopify/orders/paid)
Options
customer tag to apply (required), required product tag, required product title
Script
{% if event.preview %}
  {
    "action": {
      "type": "shopify",
      "options": [
        "update",
        [
          "customer",
          12345
        ],
        {
          "tags": {{ options.customer_tag_to_apply__required | json }}
        }
      ]
    }
  }
{% elsif order.customer %}
  {% assign purchased_product_tags = order.line_items | map: "product" | map: "tags" | join: ", " | split: ", " | sort | uniq %}
  {% assign purchased_product_titles = order.line_items | map: "product" | map: "title" | sort | uniq %}

  {
    "log": {
      "purchased_product_tags": {{ purchased_product_tags | json }},
      "purchased_product_titles": {{ purchased_product_titles | json }}
    }
  }

  {% assign order_qualifies = false %}
  {% if options.required_product_tag != blank and purchased_product_tags contains options.required_product_tag %}
    {% assign order_qualifies = true %}
  {% elsif options.required_product_title != blank and purchased_product_titles contains options.required_product_title %}
    {% assign order_qualifies = true %}
  {% endif %}

  {% if order_qualifies %}
    {% assign existing_tags = order.customer.tags | split: ", " %}
    {% if existing_tags contains tags_to_apply %}
      {
        "log": {
          "message": "Customer is already tagged",
          "customer_id": {{ order.customer.id | json }},
          "customer_tags": {{ order.customer.tags | json }}
        }
      }
    {% else %}
      {% capture tags_to_apply %}{% if order.customer.tags != blank %}{{ order.customer.tags }}, {% endif %}{{ options.customer_tag_to_apply__required }}{% endcapture %}

      {
        "action": {
          "type": "shopify",
          "options": [
            "update",
            [
              "customer",
              {{ order.customer.id | json }}
            ],
            {
              "tags": {{ tags_to_apply | json }}
            }
          ]
        }
      }
    {% endif %}
  {% else %}
    {
      "log": {
        "message": "Order does not qualify for customer tagging"
      }
    }
  {% endif %}
{% endif %}
Yep, that’s just Liquid! If this is interesting to you, check out our documentation! Mechanic is hugely developer-friendly. :)