Delete the oldest x products from a specific collection, with Mechanic.

Mechanic is an automation development platform for Shopify. :)

Delete the oldest x products from a specific collection

by Isaac Bowen (team@usemechanic.com)

Either triggered manually, or configured to run daily, this task will look for the oldest products in the collection of your choice, and delete as many of them as you wish.

Runs when a user triggers the task. Configuration includes collection, number of products to delete at once, test mode, and run daily.

15-day free trial – unlimited tasks

Documentation

This task requires a collection ID - learn how to find yours.

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)
Options
collection (number, required), number of products to delete at once (number, required), test mode (boolean), run daily (boolean)
Script
{% assign collection = shop.collections[options.collection_id__number_required] %}

{% if event.preview != true and collection == nil %}
  {"error": {{ options.collection_id__number_required | json | prepend: "Unable to find collection " | json }}}
{% endif %}

{% assign products = collection.products %}

{% if event.preview %}
  {% assign products = array %}
  {% assign products[0] = '{"id":12345,"created_at":"2000-01-01"}' | parse_json %}

  {% comment %}
    Uncomment me for more testing!
    {% assign products[1] = '{"id":67890,"created_at":"2001-01-01"}' | parse_json %}
  {% endcomment %}
{% endif %}

{% assign products_sorted = products | sort: "created_at" %}

{% assign product_ids_to_delete = array %}
{% for product in products_sorted %}
  {% if forloop.index > options.number_of_products_to_delete_at_once__number_required %}
    {% break %}
  {% endif %}

  {% assign product_ids_to_delete[product_ids_to_delete.size] = product.id %}
{% endfor %}

{% if options.test_mode__boolean %}
  {% action "echo" %}
    {"product_ids_to_delete": {{ product_ids_to_delete | json }}}
  {% endaction %}
{% else %}
  {% for product_id in product_ids_to_delete %}
    {% action "shopify" %}
      [
        "delete",
        [
          "product",
          {{ product_id | json  }}
        ]
      ]
    {% endaction %}
  {% endfor %}
{% endif %}
Mechanic tasks are written in Liquid, which makes them easy to write and easy to modify. Learn more about our platform.