Keep SKUs up to date with barcodes, with Mechanic.

Mechanic is a development platform for Shopify. :)

Keep SKUs up to date with barcodes

by Isaac Bowen (team@usemechanic.com)

Included as a good example of keeping one attribute synced up with another, this task copies new barcode values over to the variant SKU, whenever a barcode is found and the SKU is out of date.

Runs when a product is created and when a product is updated.

15-day free trial – unlimited tasks

Documentation

This task watches for new and updated products, copying variant barcodes over to the variant SKU. This occurs whenever a barcode is found, and the related variant's SKU does not already have that value.

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 product is created (shopify/products/create)
when a product is updated (shopify/products/update)
Script
{% if event.preview %}
  {% capture product_json %}
    {
      "variants": [
        {
          "admin_graphql_api_id": "gid://shopify/ProductVariant/1234567890",
          "barcode": "ABC123",
          "sku": ""
        }
      ]
    }
  {% endcapture %}

  {% assign product = product_json | parse_json %}
{% endif %}

{% for variant in product.variants %}
  {% if variant.barcode != blank and variant.sku != variant.barcode %}
    {% action "shopify" %}
      mutation {
        productVariantUpdate(
          input: {
            id: {{ variant.admin_graphql_api_id | json }}
            sku: {{ variant.barcode | json }}
          }
        ) {
          productVariant {
            barcode
            sku
          }
          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.