Auto-tag orders by product collections, with Mechanic.

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

Auto-tag orders by product collections

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 Occurs whenever an order is created, Occurs when a user manually triggers the task, and Occurs when a bulk operation is completed. Configuration includes collections and tags.

15-day free trial – unlimited tasks

Documentation

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.

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!

Run this task manually to scan and tag every order in your store. (To process orders older than 60 days, enable "read all orders".)

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
mechanic/user/trigger
mechanic/shopify/bulk_operation
Tasks use subscriptions to sign up for specific kinds of events. Learn more
Options
collections and tags (keyval, required)
Code
{% assign collections_and_tags = options.collections_and_tags__keyval_required %}

{% if event.topic == "shopify/orders/create" %}
  {% assign existing_tags = order.tags | split: ", " %}

  {% comment %}
    -- get product IDs from order line items to build the collections search query
  {% endcomment %}

  {% assign order_product_ids = order.line_items | map: "product_id" | compact | uniq %}

  {% if order_product_ids == blank %}
    {% unless event.preview %}
      {% log "This order does not contain any products from the shop catalog." %}
      {% break %}
    {% endunless %}
  {% endif %}

  {% assign search_query_parts = array %}

  {% for order_product_id in order_product_ids %}
    {% assign search_query_parts[search_query_parts.size] = order_product_id | prepend: "product_id:" %}
  {% endfor %}

  {% assign search_query = search_query_parts | join: " OR " %}

  {% unless event.preview %}
    {% log search_query: search_query %}
  {% endunless %}

  {% comment %}
    -- get collections that contain any of this order's products
  {% endcomment %}

  {% assign cursor = nil %}
  {% assign order_collections = array %}

  {% for n in (1..10) %}
    {% capture query %}
      query {
        collections(
          first: 250
          after: {{ cursor | json }}
          query: {{ search_query | json }}
        ) {
          pageInfo {
            hasNextPage
            endCursor
          }
          nodes {
            id
            legacyResourceId
            title
            handle
          }
        }
      }
    {% endcapture %}

    {% assign result = query | shopify %}

    {% if event.preview %}
      {% capture result_json %}
        {
          "data": {
            "collections": {
              "nodes": [
                {
                  "id": "gid://shopify/Collection/1234567890",
                  "legacyResourceId": "1234567890",
                  "title": "Best Widgets",
                  "handle": "best-widgets"
                }
              ]
            }
          }
        }
      {% endcapture %}

      {% assign result = result_json | parse_json %}
    {% endif %}

    {% assign order_collections = order_collections | concat: result.data.collections.nodes %}

    {% if result.data.collections.pageInfo.hasNextPage %}
      {% assign cursor = result.data.collections.pageInfo.endCursor %}
    {% else %}
      {% break %}
    {% endif %}
  {% endfor %}

  {% if order_collections == blank %}
    {% unless event.preview %}
      {% log "This order does not contain any products that belong to any collections." %}
      {% break %}
    {% endunless %}
  {% endif %}

  {% comment %}
    -- save the collection IDs, titles, and handles for comparison against the configured collections
  {% endcomment %}

  {% assign order_collection_ids = order_collections | map: "legacyResourceId" %}
  {% assign order_collection_titles = order_collections | map: "title" %}
  {% assign order_collection_handles = order_collections | map: "handle" %}

  {% log
    order_collection_ids: order_collection_ids,
    order_collection_titles: order_collection_titles,
    order_collection_handles: order_collection_handles
  %}

  {% comment %}
    -- add order tags for any matched collections
  {% endcomment %}

  {% assign tags_to_add = array %}

  {% for pair in collections_and_tags %}
    {% assign required_collection = pair[0] %}
    {% assign tags = pair[1] | split: "," %}

    {% if order_collection_ids contains required_collection
      or order_collection_titles contains required_collection
      or order_collection_handles contains required_collection
    %}
      {% for tag in tags %}
        {% assign stripped_tag = tag | strip %}

        {% unless existing_tags contains stripped_tag %}
          {% assign tags_to_add = tags_to_add | push: stripped_tag %}
        {% endunless %}
      {% endfor %}
    {% endif %}
  {% endfor %}

  {% if event.preview %}
    {% assign tags_to_add[0] = collections_and_tags.first.last %}
  {% endif %}

  {% if tags_to_add != blank %}
    {% action "shopify" %}
      mutation {
        tagsAdd(
          id: {{ order.admin_graphql_api_id | json }}
          tags: {{ tags_to_add | uniq | json }}
        ) {
          userErrors {
            field
            message
          }
        }
      }
    {% endaction %}
  {% endif %}

{% elsif event.topic == "mechanic/user/trigger" %}
  {% capture bulk_operation_query %}
    query {
      orders {
        edges {
          node {
            __typename
            id
            tags
            lineItems {
              edges {
                node {
                  __typename
                  id
                  product {
                    id
                    collections {
                      edges {
                        node {
                          __typename
                          id
                          legacyResourceId
                          title
                          handle
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  {% endcapture %}

  {% action "shopify" %}
    mutation {
      bulkOperationRunQuery(
        query: {{ bulk_operation_query | json }}
      ) {
        bulkOperation {
          id
          status
        }
        userErrors {
          field
          message
        }
      }
    }
  {% endaction %}

{% elsif event.topic == "mechanic/shopify/bulk_operation" %}
  {% if event.preview %}
    {% capture bulkOperation_objects_jsonl %}
      {"__typename":"Order","id":"gid:\/\/shopify\/Order\/1234567890","tags":[]}
    {% endcapture %}

    {% assign bulkOperation = hash %}
    {% assign bulkOperation["objects"] = bulkOperation_objects_jsonl | parse_jsonl %}
  {% endif %}

  {% assign orders = bulkOperation.objects | where: "__typename", "Order" %}
  {% assign line_items = bulkOperation.objects | where: "__typename", "LineItem" %}
  {% assign collections = bulkOperation.objects | where: "__typename", "Collection" %}

  {% for order in orders %}
    {% assign tags_to_add = array %}
    {% assign order_collections = nil %}

    {% assign order_line_items = line_items | where: "__parentId", order.id %}

    {% for line_item in order_line_items %}
      {% assign line_item_collections = collections | where: "__parentId", line_item.id %}
      {% assign order_collections = order_collections | concat: line_item_collections %}
    {% endfor %}

    {% assign order_collections = order_collections | compact %}
    {% assign order_collection_ids = order_collections | map: "legacyResourceId" %}
    {% assign order_collection_titles = order_collections | map: "title" %}
    {% assign order_collection_handles = order_collections | map: "handle" %}

    {% for pair in collections_and_tags %}
      {% assign required_collection = pair[0] %}
      {% assign tags = pair[1] | split: "," %}

      {% if order_collection_ids contains required_collection
        or order_collection_titles contains required_collection
        or order_collection_handles contains required_collection
      %}
        {% for tag in tags %}
          {% assign stripped_tag = tag | strip %}

          {% unless order.tags contains stripped_tag %}
            {% assign tags_to_add[tags_to_add.size] = stripped_tag %}
          {% endunless %}
        {% endfor %}
      {% endif %}
    {% endfor %}

    {% if event.preview %}
      {% assign tags_to_add[0] = collections_and_tags.first.last %}
    {% endif %}

    {% if tags_to_add != blank %}
      {% action "shopify" %}
        mutation {
          tagsAdd(
            id: {{ order.id | json }}
            tags: {{ tags_to_add | uniq | json }}
          ) {
            userErrors {
              field
              message
            }
          }
        }
      {% endaction %}
    {% endif %}
  {% endfor %}
{% endif %}
Task code is written in Mechanic Liquid, an extension of open-source Liquid enhanced for automation. Learn more
Defaults
Collections and tags
{"Summer Swimware" => "summer, swimware", "Cold Weather Gear" => "winter"}