Last active
May 10, 2018 14:01
-
-
Save unofficialshopify/e2c2fdb3567b5b846a9e3472c530cc2d to your computer and use it in GitHub Desktop.
How to add last or past orders in the cart in shopify. Add this liquid code under snippets folder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% if order.line_items.size > 0 %} | |
<p> | |
<button class="btn place-same-order">Add order to cart</button> | |
<script> | |
(function(){ | |
/* Check for the button */ | |
var buttonOrder = document.getElementsByClassName('place-same-order') || false; | |
if(!buttonOrder){ return } | |
/* Setup the order object. Extend this as needed. */ | |
var order = { | |
items:[ | |
{% for line_item in order.line_items %} | |
{ | |
variant_id: {{ line_item.variant.id | json }}, | |
product_id: {{ line_item.product.id | json }}, | |
properties: {{ line_item.properties | json }}, | |
available: {{ line_item.variant.available | json }} | |
}{% unless forloop.last %},{% endunless %} | |
{% endfor %} | |
] | |
}; | |
/* Simple function to check the queue */ | |
var checkQueue = function(){ | |
order.items.shift(); | |
if(order.items.length){ | |
orderItems() | |
}else{ | |
window.location.href = '/cart'; | |
} | |
}; | |
/* Simple function add to cart */ | |
var orderItems = function(){ | |
if(!order.items.length){ return } | |
if(!order.items[0].available){ | |
checkQueue(); | |
} | |
var request = new XMLHttpRequest(); | |
request.open('post', '/cart/add.js', true); | |
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); | |
request.onload = function() { | |
var resp = request.responseText; | |
if (request.status >= 200 && request.status < 400) { | |
checkQueue(); | |
} else { /* add your error handling in here */ } | |
}; | |
request.onerror = function() { | |
/* add your error handling in here */ | |
}; | |
request.send(JSON.stringify({ | |
'quantity':order.items[0].quantity, | |
'id':order.items[0].variant_id | |
})); | |
}; | |
buttonOrder[0].addEventListener("click", function (event) { | |
event.preventDefault(); | |
/* Get the button we just clicked */ | |
var t = event.target || event.srcElement; | |
/* Very simple method to stop a double click. You should make something fancier. */ | |
t.setAttribute('disabled','disabled'); | |
t.innerHTML = 'Adding to cart...'; | |
/* Fire the function that adds to cart */ | |
orderItems(); | |
}); | |
})(); | |
</script> | |
</p> | |
{% endif %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment