Skip to content

Instantly share code, notes, and snippets.

@michelarteta
Last active August 16, 2023 15:47
Show Gist options
  • Save michelarteta/c909b395e260b582fcd700936b52a67a to your computer and use it in GitHub Desktop.
Save michelarteta/c909b395e260b582fcd700936b52a67a to your computer and use it in GitHub Desktop.
Shopify Adds Custom Attributes to Checkout
const citTag = '123456789';
const store = {
order_attributes: [
'citNumberId'
]
}
const storeOrderData = {
attributes: {
citNumberId: citTag
}
};
const { attributes } = storeOrderData;
function injectInputs(element, orderAttributes) {
orderAttributes.forEach((attribute) => {
const $input = document.querySelectorAll(`input[name="checkout[attributes][${attribute}]"]`);
if ($input.length < element.length) {
const $newInput = document.createElement('input');
$newInput.type = 'hidden';
$newInput.name = `checkout[attributes][${attribute}]`;
element.appendChild($newInput);
}
});
}
function setStoreAttributes(data, orderAttributes) {
orderAttributes.forEach((attribute) => {
const $inputs = document.querySelectorAll(`input[name="checkout[attributes][${attribute}]"]`);
$inputs.forEach((input) => {
input.value = data[`${attribute}`];
});
});
}
function updateAttributes() {
const $cartForms = document.querySelectorAll('form[method="post"].edit_checkout');
if ($cartForms.length > 0) {
$cartForms.forEach((form) => {
injectInputs(form, store.order_attributes);
});
}
setStoreAttributes(attributes, store.order_attributes);
}
document.addEventListener('page:change', updateAttributes);
document.addEventListener('page:load', updateAttributes);
@giopetris
Copy link

Does it work only for Shopify Plus stores? I'm trying to do this in a non-plus store but doesn't work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment