Maintain a collection of new products, with Mechanic.

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

Maintain a collection of new products

Use this task to maintain a "New Products" collection, specifying either a number of products to include or the number of days to keep each product around. Easy! :)

Runs Occurs when a user manually triggers the task and Occurs every day at midnight (in local time). Configuration includes collection id, number of days to keep a product in this collection, and number of products to keep in this collection.

15-day free trial – unlimited tasks

Documentation

Use this task to maintain a "New Products" collection, specifying either a number of products to include or the number of days to keep each product around. Easy! :)

To use this task, create a manual collection, and add the collection ID to the task options. (Find the ID by opening the collection in the Shopify admin, then looking at the URL in your browser's address bar. If the URL is https://example.myshopify.com/admin/collections/12345, the collection ID is 12345.)

Use the "Run task" button to populate your collection for the first time. After that, this task will run daily, at midnight in your local timezone. During each run, the task will update the collection, adding new products and removing old ones as appropriate.

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
mechanic/user/trigger
mechanic/scheduler/daily
Tasks use subscriptions to sign up for specific kinds of events. Learn more
Options
collection id (number, required), number of days to keep a product in this collection (number), number of products to keep in this collection (number)
Code
{% assign collection = shop.collections[options.collection_id__number_required] %}
{% assign days_to_keep_products = options.number_of_days_to_keep_a_product_in_this_collection__number %}
{% assign product_count = options.number_of_products_to_keep_in_this_collection__number %}

{% if event.preview %}
  {% capture collection_json %}
    {
      "admin_graphql_api_id": "gid://shopify/Collection/1234567890",
      "products": [
        {
          "admin_graphql_api_id": "gid://shopify/Product/9876543210"
        }
      ]
    }
  {% endcapture %}

  {% assign collection = collection_json | parse_json %}
{% endif %}

{% if collection == blank %}
  {% error "Configured collection ID does not exist in this shop." %}
{% endif %}

{% if days_to_keep_products == blank and product_count == blank %}
  {% error %}
    "Please fill in either \"Number of days to keep a product in this collection\" or \"Number of products to keep in this collection\" (but not both!)."
  {% enderror %}
{% elsif days_to_keep_products != blank and product_count != blank %}
  {% error "Please choose one of the options, but not both! :)" %}
{% endif %}

{% assign loop_count = 100 %}
{% assign first_elements = 250 %}
{% assign products_query = "status:active" %}

{% if days_to_keep_products != blank %}
  {% if days_to_keep_products < 1 %}
    {% error %}
      "\"Number of days to keep a product in this collection\" should be > 0"
    {% enderror %}
  {% endif %}

  {% assign now_s = "now" | date: "%s" | times: 1 %}
  {% assign days_to_keep_products_s = days_to_keep_products | times: 86400 %}
  {% assign created_at_threshold_s = now_s | minus: days_to_keep_products_s %}
  {% assign created_at_threshold = created_at_threshold_s | date: "%Y-%m-%d" %}
  {% assign products_query = products_query
    | append: " created_at:>="
    | append: created_at_threshold
  %}
{% elsif product_count != blank %}
  {% if product_count < 1 %}
    {% error %}
      "\"Number of products to keep in this collection\" should be > 0"
    {% enderror %}
  {% endif %}

  {% assign loop_count = product_count | divided_by: 250 %}
  {% assign remaining = product_count | modulo: 250 %}
{% endif %}

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

{% for n in (0..loop_count) %}
  {% if product_count != blank %}
    {% if forloop.last %}
      {% if remaining == 0 %}
        {% break %}
      {% endif %}

      {% assign first_elements = remaining %}
    {% endif %}
  {% endif %}

  {% capture query %}
    query {
      products(
        first: {{ first_elements }}
        after: {{ cursor | json }}
        query: {{ products_query | json }}
        reverse: true
        sortKey: CREATED_AT
      ) {
        pageInfo {
          hasNextPage
        }
        edges {
          cursor
          node {
            id
          }
        }
      }
    }
  {% endcapture %}

  {% assign result = query | shopify %}

  {% if event.preview %}
    {% capture result_json %}
      {
        "data": {
          "products": {
            "edges": [
              {
                "node": {
                  "id": "gid://shopify/Product/1234567890"
                }
              }
            ]
          }
        }
      }
    {% endcapture %}

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

  {% assign result_product_ids = result.data.products.edges | map: "node" | map: "id" %}
  {% assign qualifying_product_ids = qualifying_product_ids | concat: result_product_ids %}

  {% if result.data.products.pageInfo.hasNextPage %}
    {% assign cursor = result.data.products.edges.last.cursor %}
  {% else %}
    {% break %}
  {% endif %}
{% endfor %}

{% assign current_product_ids =  collection.products | map: "admin_graphql_api_id" %}

{% assign product_ids_to_add = array %}
{% assign product_ids_to_remove = array %}

{% for qualifying_product_id in qualifying_product_ids %}
  {% unless current_product_ids contains qualifying_product_id %}
    {% assign product_ids_to_add = product_ids_to_add | push: qualifying_product_id %}
  {% endunless %}
{% endfor %}

{% for current_product_id in current_product_ids %}
  {% unless qualifying_product_ids contains current_product_id %}
    {% assign product_ids_to_remove = product_ids_to_remove | push: current_product_id %}
  {% endunless %}
{% endfor %}

{% assign mutations = array %}

{% if product_ids_to_add != blank  %}
  {% assign groups_of_product_ids_to_add = product_ids_to_add | in_groups_of: 250, fill_with: false %}

  {% for group_of_product_ids_to_add in groups_of_product_ids_to_add %}
    {% capture mutation %}
      collectionAddProducts{{ forloop.index0 }}: collectionAddProducts(
        id: {{ collection.admin_graphql_api_id | json }}
        productIds: {{ group_of_product_ids_to_add | json }}
      ) {
        userErrors {
          field
          message
        }
      }
    {% endcapture %}

    {% assign mutations = mutations | push: mutation %}
  {% endfor %}
{% endif %}

{% if product_ids_to_remove != blank  %}
  {% assign groups_of_product_ids_to_remove = product_ids_to_remove | in_groups_of: 250, fill_with: false %}

  {% for group_of_product_ids_to_remove in groups_of_product_ids_to_remove %}
    {% capture mutation %}
      collectionRemoveProducts{{ forloop.index0 }}: collectionRemoveProducts(
        id: {{ collection.admin_graphql_api_id | json }}
        productIds: {{ group_of_product_ids_to_remove | json }}
      ) {
        userErrors {
          field
          message
        }
      }
    {% endcapture %}

    {% assign mutations = mutations | push: mutation %}
  {% endfor %}
{% endif %}

{% if mutations != blank %}
  {% action "shopify" %}
    mutation {
      {{ mutations | join: newline }}
    }
  {% endaction %}
{% else %}
  {% log "This collection already has the correct products." %}
{% endif %}
Task code is written in Mechanic Liquid, an extension of open-source Liquid enhanced for automation. Learn more