Skip to content

Instantly share code, notes, and snippets.

@davelowensohn
Created May 2, 2017 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davelowensohn/c2af5ba1ed10a637b6bd16e7942f7bd0 to your computer and use it in GitHub Desktop.
Save davelowensohn/c2af5ba1ed10a637b6bd16e7942f7bd0 to your computer and use it in GitHub Desktop.
Shopify canonicalize product into first collection
...
{% if product.collections[0].handle.size > 0 %}
{% assign canonical_url = shop.url | append: '/collections/' | append: product.collections[0].handle | append: '/products/' | append: product.handle %}
{% else %}
{% assign canonical_url = product.url | within: collection %}
{% endif %}
...
<script>
// Force canonicalization into product.collections[0]
// Nasty workaround for forcibly redirecting old /products/ links
jQuery(document).ready(function($){
var current_url = document.URL,
canonical_url_stub = $('#canonicalHref').attr('href'),
returnUrl;
if (!canonical_url_stub) {
// console.log('no stub!');
return;
} else if (current_url.includes('/collections')) {
// console.log('already in collection:', current_url, canonical_url_stub);
return;
} else {
// console.log('reroute:', current_url, canonical_url_stub);
window.location = `${current_url.split('/products')[0]}${canonical_url_stub}` ;
return;
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment