Auto-tag customers that accept marketing, with Mechanic.

Mechanic is a development platform for Shopify. :)

Auto-tag customers that accept marketing

by Isaac Bowen (team@usemechanic.com)

Use this task to easily keep track of customers who accept marketing, adding a tag for those that do and removing it from customers who do not. Run this task manually to sync that tag for all customers.

Runs when a user triggers the task, when a customer is created, and when a customer is updated. Configuration includes customer tag to add.

15-day free trial – unlimited tasks

Documentation

Use this task to easily keep track of customers who accept marketing, adding a tag for those that do and removing it from customers who do not. Run this task manually to sync that tag for all customers.

Note: If you have many customers, running this task manually could take a long time!

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 a user triggers the task (mechanic/user/trigger)
when a customer is created (shopify/customers/create)
when a customer is updated (shopify/customers/update)
Options
customer tag to add (required)
Script
{% assign customers = array %}

{% if event.preview %}
  {% assign customer = hash %}
  {% assign customer["admin_graphql_api_id"] = "gid://shopify/Customer/1234567890" %}
  {% assign customer["accepts_marketing"] = true %}
  {% assign customer["tags"] = "" %}
  {% assign customers[0] = customer %}
{% elsif event.topic contains "shopify/customers/" %}
  {% assign customers[0] = customer %}
{% else %}
  {% assign customers = shop.customers %}
{% endif %}

{% for customer in customers %}
  {% assign customer_tags = customer.tags | split: ", " %}

  {% if customer.accepts_marketing %}
    {% unless customer_tags contains options.customer_tag_to_add__required %}
      {% action "shopify" %}
        mutation {
          tagsAdd(
            id: {{ customer.admin_graphql_api_id | json }}
            tags: {{ options.customer_tag_to_add__required | json }}
          ) {
            userErrors {
              field
              message
            }
          }
        }
      {% endaction %}
    {% endunless %}
  {% elsif customer_tags contains options.customer_tag_to_add__required %}
    {% action "shopify" %}
      mutation {
        tagsRemove(
          id: {{ customer.admin_graphql_api_id | json }}
          tags: {{ options.customer_tag_to_add__required | json }}
        ) {
          userErrors {
            field
            message
          }
        }
      }
    {% endaction %}
  {% endif %}
{% endfor %}
Mechanic tasks are written in Liquid, which makes them easy to write and easy to modify. Learn more about our platform.