Skip to content

Instantly share code, notes, and snippets.

@cole007
Last active October 27, 2021 16:10
Show Gist options
  • Save cole007/39a6df90c5055178c45a to your computer and use it in GitHub Desktop.
Save cole007/39a6df90c5055178c45a to your computer and use it in GitHub Desktop.
Shopify API filter for product prices
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8">
<title>Shopify filtering Boilerplate</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="_assets/css/style.css">
</head>
<body>
<div class="site">
<header class="header"></header>
<h1 class="heading-1">Mudstone</h1>
<form>
<input type="text" name="min" value="0" />
<input type="text" name="max" value="150" />
<input type="hidden" name="collection" value="books" />
<input type="submit" name="submit" value="submit" />
</form>
<ul class="products">
</ul>
<footer class="footer"></footer>
</div>
<script src="script.js"></script>
</body>
</html>
// requires jQuery
$(function($){
function doProducts(collection, limit) {
collection = typeof collection !== 'undefined' ? collection : 'books';
limit = typeof limit !== 'undefined' ? limit : 250;
var url = 'http://XXX.myshopify.com/collections/' + collection + '/products.json?limit=' + limit;
return url;
}
var doFilter = function(data,min,max) {
min = typeof min !== 'undefined' ? min : 0;
max = typeof max !== 'undefined' ? max : 250;
var output = new Array();
for (var i = 0; i < data.products.length; i++) {
if (data.products[i].variants[0].price >= min && data.products[i].variants[0].price <= max) {
output.push(data.products[i]);
}
}
return output;
}
$('form').on('submit',function(e) {
e.preventDefault();
var min = parseInt($(this).find('[name=min]').val());
var max = parseInt($(this).find('[name=max]').val());
var collection = $(this).find('[name=collection]').val();
var json = doProducts(collection);
var imgsrc = 'https://cdn.shopify.com/s/assets/admin/no-image-large-d7c282f81cbf208c9ee0f0f27cb214c7.gif';
$('.products').find('li').remove();
$.ajax({
type: 'GET',
url: json,
dataType: 'jsonp',
success: function (data) {
var output = doFilter(data,min,max);
for (var i = 0; i < output.length; i++) {
var item = output[i];
if (item.images.length > 0) {
var tempSrc = item.images[0].src;
} else {
var tempSrc = imgsrc;
}
$('.products').append('<li><a href="/collections/' + collection + '/products/' + item.handle + '"><img src="' + tempSrc + '" alt=""/> ' + item.title + '</a></li>');
}
}
});
});
});
@cole007
Copy link
Author

cole007 commented Mar 1, 2021

Sorry folk - this is 6 years old

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