Auto-sort collections by product properties, with Mechanic.

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

Auto-sort collections by product properties

This task re-sorts your collections by any product property that you choose. Use the "Product property lookups" option to control what attribute the task "looks up". For example, using "published_at" will result in sorting by the date and time the product was published. Add more than one lookup to dive more deeply into product data: using the lookups "metafields", "store", "priority", and "value" will result in a collection sorted by the store.priority metafield value on each product.

Runs Occurs when a user manually triggers the task, Occurs whenever user/collection_sort/process is triggered, and Occurs whenever user/collection_sort/complete is triggered. Configuration includes product property lookups, only sort these collections, reverse sort, run hourly, and run daily.

15-day free trial – unlimited tasks

Documentation

This task re-sorts your collections by any product property that you choose. Use the "Product property lookups" option to control what attribute the task "looks up". For example, using "published_at" will result in sorting by the date and time the product was published. Add more than one lookup to dive more deeply into product data: using the lookups "metafields", "store", "priority", and "value" will result in a collection sorted by the store.priority metafield value on each product.

Refer to Shopify's API documentation to find the product property you're looking for.

Run this task manually to re-sort your collections on demand, or choose to run it hourly or nightly.

This task will scan all collections in the shop on each run, unless you configure it to only sort certain collections using each collection's title or ID. The collections processed by this task must be configured for manual sorting, otherwise they will be ignored. Learn how to change the sort order of your collections.

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
user/collection_sort/process
user/collection_sort/complete
{% if options.run_hourly__boolean %}
  mechanic/scheduler/hourly
{% elsif options.run_daily__boolean %}
  mechanic/scheduler/daily
{% endif %}
Tasks use subscriptions to sign up for specific kinds of events. Learn more
Options
product property lookups (array, required), only sort these collections (array), reverse sort (boolean), run hourly (boolean), run daily (boolean)
Code
{% assign product_property_lookups = options.product_property_lookups__array_required %}
{% assign only_sort_these_collections = options.only_sort_these_collections__array %}
{% assign reverse_sort = options.reverse_sort__boolean %}

{% if event.topic == "mechanic/user/trigger" or event.topic contains "mechanic/scheduler/" %}
  {% comment %}
    -- get IDs for all manually sorted collections, optionally restricted to specific collections by ID or title
  {% endcomment %}

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

  {% for n in (1..50) %}
    {% capture query %}
      query {
        collections(
          first: 250
          after: {{ cursor | json }}
          query: {{ search_query | json }}
        ) {
          pageInfo {
            hasNextPage
            endCursor
          }
          nodes {
            legacyResourceId
            sortOrder
            title
          }
        }
      }
    {% endcapture %}

    {% assign result = query | shopify %}

    {% if event.preview %}
      {% capture result_json %}
        {
          "data": {
            "collections": {
              "nodes": [
                {
                  "legacyResourceId": "1234567890",
                  "sortOrder": "MANUAL"
                }
              ]
            }
          }
        }
      {% endcapture %}

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

    {% for collection in result.data.collections.nodes %}
      {% if only_sort_these_collections != blank %}
        {% unless only_sort_these_collections contains collection.legacyResourceId
          or only_sort_these_collections contains collection.title
          or event.preview
        %}
          {% continue %}
        {% endunless %}
      {% endif %}

      {% if collection.sortOrder != "MANUAL" %}
        {% log
          message: "Collection is not configured for manual sorting; skipping.",
          collection: collection
        %}
        {% continue %}
      {% endif %}

      {% assign collection_ids_to_sort = collection_ids_to_sort | push: collection.legacyResourceId %}
    {% endfor %}

    {% if result.data.collections.pageInfo.hasNextPage %}
      {% assign cursor = result.data.collections.pageInfo.endCursor %}
    {% else %}
      {% break %}
    {% endif %}
  {% endfor %}

  {% if collection_ids_to_sort == blank %}
    {% log "No collections qualified to be sorted on this task run." %}
    {% break %}
  {% endif %}

  {% comment %}
    -- save the qualified collection IDs to the cache for lookup in later child events
    -- NOTE: using event ID instead of task ID in case one instance of this task runs concurrent with another
  {% endcomment %}

  {% assign cache_key = event.id | prepend: "collection_ids_to_sort_" %}
  {% action "cache", "set", cache_key, collection_ids_to_sort %}

  {% log
    message: "Begin processing collections loop using sequential child events.",
    total_collections_to_sort: collection_ids_to_sort.size
  %}

  {% action "event" %}
    {
      "topic": "user/collection_sort/process",
      "task_id": {{ task.id | json }},
      "data": {
        "cache_key": {{ cache_key | json }},
        "cache_index": 0
      }
    }
  {% endaction %}

{% elsif event.topic == "user/collection_sort/process" %}
  {% assign cache_key = event.data.cache_key %}
  {% assign cache_index = event.data.cache_index %}
  {% assign collection_ids_to_sort = cache[cache_key] %}
  {% assign collection_id = collection_ids_to_sort[cache_index] %}
  {% assign collection = shop.collections[collection_id] %}

  {% if event.preview %}
    {% comment %}
      -- use stub data instead of a preview event to incorporate the configured product properties
    {% endcomment %}

    {% assign product_ids = array | push: "1234567890", "3456789012", "2345678901" %}
    {% assign products = array %}

    {% for product_id in product_ids %}
      {% assign product = hash %}

      {% for lookup in product_property_lookups reversed %}
        {% if forloop.first %}
          {% assign product[lookup] = product_id %}

        {% else %}
          {% assign temp = product %}
          {% assign product = hash %}
          {% assign product[lookup] = temp %}
        {% endif %}
      {% endfor %}

      {% assign product["id"] = product_id %}
      {% assign product["admin_graphql_api_id"] = "gid://shopify/Product/" | append: product_id %}
      {% assign products[products.size] = product %}
    {% endfor %}

    {% capture collection_json %}
      {
        "title": {{ only_sort_these_collections[0] | default: "Some collection" | json }},
        "admin_graphql_api_id": "gid://shopify/Collection/1234567890",
        "products": {{ products | json }}
      }
    {% endcapture %}

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

  {% comment %}
    -- process products using REST resources to align with configured product properties
  {% endcomment %}

  {% assign moves = array %}
  {% assign product_ids_and_positions = hash %}
  {% assign product_ids_and_values = array %}

  {% for product in collection.products %}
    {% assign product_ids_and_positions[product.admin_graphql_api_id] = forloop.index0 %}

    {% assign product_id_and_value = hash %}
    {% assign product_id_and_value["id"] = product.admin_graphql_api_id %}

    {% assign value = product %}

    {% for lookup in options.product_property_lookups__array_required %}
      {% comment %}
        -- NOTE: command methods (size, first, last) can only be invoked via dot notation
      {% endcomment %}

      {% case lookup %}
        {% when "size" %}
          {% assign value = value.size %}
        {% when "first" %}
          {% assign value = value.first %}
        {% when "last" %}
          {% assign value = value.last %}
        {% else %}
          {% assign value = value[lookup] %}
      {% endcase %}
    {% endfor %}

    {% comment %}
      -- make sure this is always a serializable/sortable object, defaulting to nil in the case of an empty string so that SKU values which are *either* nil or an empty string always end up at the end of the list.
    {% endcomment %}

    {% assign product_id_and_value["value"] = value | json | parse_json | default: nil %}

    {% assign product_ids_and_values[product_ids_and_values.size] = product_id_and_value %}
  {% endfor %}

  {% assign sorted_product_values = product_ids_and_values | sort: "value" %}
  {% assign sorted_product_ids = product_ids_and_values | sort: "value" | map: "id" %}

  {% if reverse_sort %}
    {% assign sorted_product_ids = sorted_product_ids | reverse %}
  {% endif %}

  {% comment %}
    -- determine the moves necessary to place products in their sorted positions
  {% endcomment %}

  {% for sorted_product_id in sorted_product_ids %}
    {% if forloop.index0 != product_ids_and_positions[sorted_product_id] %}
      {% assign move = hash %}
      {% assign move["id"] = sorted_product_id %}
      {% assign move["newPosition"] = "" | append: forloop.index0 %}
      {% assign moves[moves.size] = move %}
    {% endif %}
  {% endfor %}

  {% if moves == blank %}
    {% log
      message: "No moves necessary for this collection, everything is already in its appropriate sort order.",
      collection: collection.title
    %}

  {% else %}
    {% log
      message: "Collection requires sorting.",
      collection: collection.title
    %}

    {% assign moves_in_groups = moves | in_groups_of: 250, fill_with: false %}

    {% for move_group in moves_in_groups %}
      {% action "shopify" %}
        mutation {
          collectionReorderProducts(
            id: {{ collection.admin_graphql_api_id | json }}
            moves: {{ move_group | graphql_arguments }}
          ) {
            userErrors {
              field
              message
            }
          }
        }
      {% endaction %}
    {% endfor %}
  {% endif %}

  {% assign new_cache_index = cache_index | plus: 1 %}

  {% log
    collections_seen: new_cache_index,
    total_collections_to_sort: collection_ids_to_sort.size
  %}

  {% comment %}
    -- process next collection in the cache if there is one
  {% endcomment %}

  {% if new_cache_index < collection_ids_to_sort.size %}
    {% action "event" %}
      {
        "topic": "user/collection_sort/process",
        "task_id": {{ task.id | json }},
        "data": {
          "cache_key": {{ cache_key | json }},
          "cache_index": {{ new_cache_index }}
        }
      }
    {% endaction %}

  {% else %}
    {% comment %}
      -- use a distinct user event to indicate the entire task run is complete, so it can be filtered in the event log
    {% endcomment %}

    {% action "event" %}
      {
        "topic": "user/collection_sort/complete",
        "task_id": {{ task.id | json }},
        "data": {
          "cache_key": {{ cache_key | json }},
          "cache_index": {{ new_cache_index }}
        }
      }
    {% endaction %}
  {% endif %}

{% elsif event.topic == "user/collection_sort/complete" %}
  {% assign cache_key = event.data.cache_key %}
  {% assign cache_index = event.data.cache_index %}

  {% log
    message: "Collection sorting complete. Deleting cached collection IDs.",
    collections_seen: cache_index
  %}

  {% action "cache", "del", cache_key %}
{% endif %}
Task code is written in Mechanic Liquid, an extension of open-source Liquid enhanced for automation. Learn more
Defaults
Product property lookups
["published_at"]