Mechanic Get Mechanic
Task library

Auto-tag orders based on cart attributes

Use this task to automatically categorize orders based on the cart attributes configured before checkout. Useful if you allow customers to supply extra information about their order, or if your cart has some hidden coding that adds cart attributes programatically.

Try this task

When it runs

Occurs whenever an order is created

What you choose

  • Cart attribute to monitor
  • Cart attribute values and order tags to add

Documentation

Use this task to automatically categorize orders based on the cart attributes configured before checkout. Useful if you allow customers to supply extra information about their order, or if your cart has some hidden coding that adds cart attributes programatically.

Configure the "Cart attribute to monitor" option with the exact name of the cart attribute in use. This value is case-sensitive, and must include any punctuation used in the actual cart attribute.

Configure the "Cart attribute values and order tags to add" option with an attribute value on the left, and a tag on the right, to be applied when the left-hand value is found on an order. Add as many value/tag pairs as you like. :)

Task code and subscriptions

You can edit the Liquid code after installing this task. View on GitHub or ask a question in the Mechanic Slack community.

Subscriptions

shopify/orders/create
How task subscriptions work

Option types and flags

Task code

{% comment %}
  Preferred order of options:

  {{ options.cart_attribute_to_monitor__required }}
  {{ options.cart_attribute_values_and_order_tags_to_add__keyval_required }}
{% endcomment %}

{% if event.preview %}
  {% capture order_json %}
    {
      "admin_graphql_api_id": "gid://shopify/Order/12345",
      "tags": "",
      "note_attributes": {
        {{ options.cart_attribute_to_monitor__required | json }}: {{ options.cart_attribute_values_and_order_tags_to_add__keyval_required.first.first | json }}
      }
    }
  {% endcapture %}

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

{% assign attribute_name = options.cart_attribute_to_monitor__required %}
{% assign attribute_value = order.note_attributes[attribute_name] %}
{% assign tag = options.cart_attribute_values_and_order_tags_to_add__keyval_required[attribute_value] %}
{% assign order_tags = order.tags | split: ", " %}

{% if tag == blank %}
  {% log "Order does not qualify for a tag" %}
{% elsif order_tags contains tag %}
  {% log message: "Order is already tagged", tag: tag %}
{% else %}
  {% action "shopify" %}
    mutation {
      tagsAdd(
        id: {{ order.admin_graphql_api_id | json }}
        tags: {{ tag | json }}
      ) {
        userErrors {
          field
          message
        }
      }
    }
  {% endaction %}
{% endif %}
Mechanic Liquid reference