shopify

How to clear a cart's attributes in Shopify?


Previously when I visited /cart/clear or did the below, it cleared my cart, and it's attributes. Now when I do either of those things, it clears the products, but the cart attributes are persisting. I'm not sure if this is a recent change or a Shopify bug?

Any idea how to clear the cart's attributes?

$.ajax({
  type: "POST",
  url: '/cart/clear.js',
  success: function(){
    alert('You cleared the cart!');
  },
  dataType: 'json'
});

Solution

  • I've found a way to delete them all by doing this, which seems overly complicated, but it works.

    $.ajax({
        type: "GET",
        url: '/cart.js',
        dataType: 'json',
        success: function(resp) { 
            var nullHash = {};
            for ([key, value] of Object.entries(resp.attributes)) {    
                nullHash[key] = null;
            }
            $.ajax({
                type: "POST",
                url: '/cart/update.js',
                data: {attributes:nullHash},
                dataType: 'json'
            });
        }
    });
    

    Or if you want to delete them by name, you can do this:

    var nullHash = {
        'someAtt1': null,
        'someAtt2': null,
        'someAtt3': null
    };
    $.ajax({
        type: "POST",
        url: '/cart/update.js',
        data: {attributes:nullHash},
        dataType: 'json'
    });