Delete variants having a metafield date that has passed with Mechanic.

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

Delete variants having a metafield date that has passed

by Isaac Bowen (team@usemechanic.com)

Do you sell tickets to recurring events? Do you use a new product variant for each one? Use this task to regularly scan your catalog for product variants that have a date metafield, and to delete variants when their date has passed.

Runs when a user triggers the task and every day at midnight. Configuration includes date metafield namespace and date metafield key.

15-day free trial – unlimited tasks

Documentation

Run this task manually to immediately scan your product catalog for outdated variants, and delete them. This task will also run nightly, at midnight in your store's timezone.

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)
every day at midnight (mechanic/scheduler/daily)
Options
date metafield namespace (required), date metafield key (required)
Script
{% if event.preview %}
  {
    "action": {
      "type": "shopify",
      "options": [
        "delete",
        ["variant", {{ variant.id | json }}]
      ]
    }
  }
{% else %}
  {% assign today = "now" | date: "%Y-%m-%d" %}

  {% for product in shop.products.published %}
    {% if product.variants.size == 1 and product.variants[0].title == "Default Title" %}
      {% continue %}
    {% endif %}

    {% for variant in product.variants %}
      {% assign expiration_date = variant.metafields[options.date_metafield_namespace__required][options.date_metafield_key__required] %}
      {% if expiration_date != blank and expiration_date < today %}
        {
          "action": {
            "type": "shopify",
            "options": [
              "delete",
              ["variant", {{ variant.id | json }}]
            ]
          }
        }
      {% endif %}
    {% endfor %}
  {% endfor %}
{% endif %}
Mechanic tasks are written in Liquid, which makes them easy to write and easy to modify. Learn more about our platform.