Skip to content

Instantly share code, notes, and snippets.

@christophergregory
Created December 3, 2012 16:05
Show Gist options
  • Save christophergregory/4195957 to your computer and use it in GitHub Desktop.
Save christophergregory/4195957 to your computer and use it in GitHub Desktop.
Shopify:Remove old attributes from the cart
function getCartData(callback) {
Shopify.getCart(function(cart){
callback(cart);
});
}
function updateCartAttributes(data, callback) {
var params = {
type: 'POST',
url: '/cart/update.js',
data: data,
dataType: 'json',
success: function(cart) {
if ((typeof callback) === 'function') {
callback(cart);
}
else {
Shopify.api.onCartUpdate(cart);
}
},
error: function(XMLHttpRequest, textStatus) {
Shopify.api.onError(XMLHttpRequest, textStatus);
}
};
$.ajax(params);
}
// Removes cart attributes for items that have been removed from the cart
function removeOldAttributes() {
getCartData(function(cart){
var attrs = cart.attributes,
items = cart.items,
itemsToRemove = {};
for (attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
if (attr.indexOf('Backordered') !== -1) {
var attrTitle = attr.split("- ")[1],
removeAttr = false;
for (itm in items) {
if (items.hasOwnProperty(itm)) {
var title = items[itm].title;
if (title.indexOf(attrTitle) === -1) {
removeAttr = true;
itemsToRemove["attributes[" + attr + "]"] = "";
}
}
}
}
}
}
updateCartAttributes(itemsToRemove, function(cart){
// Perform additional actions if needed.
});
});
}
// removeOldAttributes();
@maddogprod
Copy link

Does this code do what I think it does? I just opened a store and use Cart Attributes, and found that if someone deletes an item after filling in the Attribute, it's not deleted. Will this code take care of that? Where would I add it?

THANKS

@christophergregory
Copy link
Author

Hi maddogprod, I just realized there was a comment on here. Do you still need help with this? I would be happy to give you a few pointers.

@titusjin
Copy link

hi Christopher :
first, thanks for the code !
second, how we can use Shopify object in checkout page ?

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