Last active
January 10, 2023 02:31
-
-
Save resistorsoftware/1080296 to your computer and use it in GitHub Desktop.
You Might Like This! Shopify Related Products App
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
<!-- | |
* a simple HTML DOM element for rendering related products. | |
* Style with CSS to make the <ul> look like whatever you want. | |
* place this snippet in your product.liquid where you would like the related products to appear | |
--> | |
<div id="related-products-container"> | |
<h1>YOU MIGHT LIKE THIS!</h1> | |
<div id="related"> | |
<ul class="related"> | |
</ul> | |
</div> | |
</div> | |
{% comment %} | |
- a simple Liquid snippet that will sniff out any related products set by the App | |
- the handles are available in the hidden div element, and handles can be used by Javascript to get all the product details | |
- this means you have access to prices, images, variants, every property of a product. | |
- it does not really matter where in product.liquid this snippet exists | |
{% endcomment %} | |
{% assign mf = product.metafields.related %} | |
{% unless mf == empty %} | |
{% for mf in product.metafields.related %} | |
{% if mf.first == 'related' and mf.last != '' %} | |
<div id="related_products_data" style="display:none;"> | |
{{mf.last}} | |
</div> | |
{% endif %} | |
{% endfor %} | |
{% endunless %} | |
<!-- | |
* A simple template used to stamp out related products | |
* this can be whatever you want or need in terms of HTML DOM elements | |
* I provide this simple unordered list, and the template provides the <li> elements for the ul of class "related" | |
* this script can be placed anywhere in your product.liquid template | |
--> | |
<script id="relatedTemplate" type="text/x-jquery-tmpl"> | |
<li> | |
<a href="${url}"> | |
<img src="${src}" alt="${title}" height="50" width="50" /> | |
</a> | |
</li> | |
</script> | |
<script type="text/javascript"> | |
// <![CDATA[ | |
$(function() { | |
// a simple jQuery DOM loaded function. | |
// sniff inside the related_products_data element for handles to the related products | |
// use the standard Shopify Javascript API to get the products | |
var rp = $("#related_products_data").text(); | |
if(rp) { | |
$.each(rp.split(","), function (idx, val) { | |
Shopify.getProduct(val.replace(/\s/g,""), function(product) { | |
var src = (typeof product.images[0] == 'undefined')? "" : product.images[0].replace(/\.jpeg/,"_small.jpeg"); | |
$("#relatedTemplate" ).tmpl({url: product.url, src: src, title: product.title}).appendTo("ul.related"); | |
}); | |
}); | |
} | |
}); | |
// ]]> | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment