Shopify Hide Best Sellers - shopify

I'm trying to hide access from competition viewing the best-sellers, specifically using a URL like this:
www.store.myshopify.com/collections/all?sort_by=best-selling
I've tried {% if collection.url contains 'sort_by=best-selling' %} but that doesn't work. Is there any way to target a URL with an attached query string?
If not, any suggestions?
Thanks!

Unfortunately collection.url doesn't return the query string, in your example, it would output /collections/all
I don't think there's a way in Liquid to get the current url query string. You can only set the default sort type with collection.default_sort_by : 'price'
Or to override all sorting with {% assign products = collection.products | sort: 'price' %}
You can override the sort_by query string parameter using jQuery to substitute best-selling by price:
<script type="text/javascript">
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
var sort_by = $.urlParam('sort_by');
if(sort_by == "best-selling") {
var url = window.location.href;
url = url.replace("best-selling", "price"); // override to sort by price
window.location.href = url; // redirect to url
}
<script>
Using this code with your example, it would automatically redirect the page www.store.myshopify.com/collections/all?sort_by=best-selling to www.store.myshopify.com/collections/all?sort_by=price
But keep in mind that your competitors could disable that JS code and still access the best-selling items.

Related

how to get url parameters using shopify liquid?

I have a landing page that contains the add to cart button with the product handle like this:
shopifystorename.com/some-product-handle
What I want is to redirect automatically or the product be added automatically to the shopify cart if the user lands on that url above. I've tried using JS:
let m = window.location.href;
var n = m.lastIndexOf('/');
var result = m.substring(n+1);
console.log(result);
var span = document.getElementById("handle");
span.textContent = result;
And capture it on shopify liquid like so:
{% capture my_variable %}<span id="handle">test</span>{% endcapture %}
{{ my_variable }}
{{ all_products[my_variable].title }}
But I'm not getting the value or it is not updated.
It won't work. Liquid is for server-side rendering engine and JS is for frontend. You'll need to purely use Javascript here to make use of AJAX API of Shopify and in a more refined and simple way.
var thisProduct = await fetch('/products/'+ location.pathname +'.js').then(p => { return p.json(); });
alert('The title of this product is ' + thisProduct.title);

Disable checkout if all products do not share same tag Shopify

I have a custom checkout experience in my Shopify store that I only want to allow if all products in the cart contain the tag "test"
This is the function I currently have, which seems to only work with a single item in the cart.
function productTags() {
{%- assign tagEnabled = false -%}
return {
{%- for item in cart.items -%}
{%- if item.product.tags contains 'test' -%}
"{{ item.product.tags }}": {{ item.quantity | json }}
{%- assign tagEnabled = true -%}
{%- endif -%}
{%- endfor -%}
};
}
this line ( "{{ item.product.tags }}": {{ item.quantity | json }}) is only there for display in the console when testing this. I can remove that if necessary.
How can I expand this to look for all item tags in the cart, and only assign the tagEnabled variable to true if all of them have the same tag?
Thanks in advance!
It looks like you are trying to mix Liquid with Javascript, which can make coding confusing. I would recommend splitting your code into two parts: one where you collect your Liquid variables and assign them to Javascript variables (and I see you are using the json filter to do that already, which is awesome - that filter guarantees that your variable output will be in a Javascript-legal format), and the second part where you write your Javascript code without any Liquid brackets getting in the way. (This is especially helpful if you are using a code editor with any syntax or error highlighting)
Let me know if the following helps you get the information you need:
// The Liquid filter 'map' lets you drill into nested object properties. We can use this to get an array of tag arrays.
// The JSON Liquid filter will turn any Liquid variable into a legal Javascript variable.
const itemProductTags = {{ cart.items | map: 'product'| map: 'tags' | json }}
// Check on our variables
console.log('All product tag arrays', itemProductTags)
console.log('Results of tagCheck()', tagCheck(itemProductTags, 'test') )
function tagCheck(tagsList, targetTag){
// Checks to see if the targetTag appears in all, some or none of the tag arrays.
// tagsList will be an array of arrays
var targetInAny = false;
var targetInAll = true;
for(var i=0; i<tagsList.length; i++){
var tags = tagsList[i];
if(tags.indexOf(targetTag) != -1){
// Found the tag - this targetTag appears in at least one product-tag list
targetInAny = true;
}
else{
// Did not find the tag - this targetTag is NOT in every product-tag list
targetInAll = false;
}
}
// Returns an object specifying if we found the target in any, all or none of the lists
return { targetInAny: targetInAny, targetInAll: targetInAll, targetInNone: !targetInAny }
}

Passing {{raw}} variable to snippet - Shopify

I have created a simple AJAX request which feeds back to the header template. However, I can not seem to be able to do any of the following assign, capture, render, include.
<script id="CartPopover" type="text/x-handlebars-template">
{% raw %}
{{#items}}
{% render "cart-item", item: item %}
{{/items}}
{% endraw %}
</div>
Update
I am attempting to update the sliding side cart on the website when a product is added to cart. Please see the ajax, /cart/add.js success
function below.
var showCartNotificationPopup = function (product) {
var addedQuantity = parseInt($('.quantity__input', this.$container).val());
$.get("/cart.json", function (data) {
var cart_items = data.items
$.each(cart_items, function (index, item) {
item.minus_quatinty = item.quantity - 1;
item.formatPrice = Shopify.formatMoney(item.final_price)
})
cart = {
items: data.items
}
$("#side-cart-container").find(".item").detach();
$("#CartOuter table tbody").prepend(template(cart));
console.log(cart);
$("#side-cart-container").addClass("visible");
});
clearTimeout(popoverTimer);
}
You are misunderstanding how Shopify works. Liquid code is parsed once by Shopify when a page is loaded. Shopify creates a huge string of HTML, CSS and JS and dumps it into the browser.
Once you are in the land of Javascript, you no longer play with Liquid. Instead, you play with data. So, if you want to update the cart, you use Javascript. If you want to know what is in the cart, you use Javascript. If you want to re-render the contents of the cart, you replace the DOM you no longer like with new DOM. Use Javascript templates for this.
No amount of Liquid in your JS will help you except during render time. At render time, you can certainly build and fill a Javascript data structure with data from Liquid.

Use js variable with Shopify liquid tag

Currently in Shopify we can create a file.js.liquid which grants access to liquid functionality.
<script>
var liquidData = {
myValue: {{ product.image | asset_url }}
}
</script>
How can I use a variable in the placeme of product.image?
In example:
var myVar = 'something.jpg'
var liquidData = {
myValue: {{ myVar | asset_url }}
}
Currently this does not work for me the path it out puts is myVar as a string not as a variable. I also tried concatenation and it also reads the variable name as a string. Any ideas?
You must remember that liquid is executed before the DOM. This applies to Javascript files as well.
The liquid code is executed before the JS file is processed so when you create a JS variable and try to pass it to liquid is not possible since liquid finished it's execution long before the Javascript started to execute.
So to sum it up you can't pass anything from the Javascript ot Liquid, but the other way is possible.
So back to your question.
It should look like so:
{% assign myVar = 'something.jpg' %}
var liquidData = {
myValue: "{{ myVar | asset_url }}"
}

in SQL, or Django ORM, what's the conventional way to have an ordered one-to-many?

Say I wanted to have a project, and one-to-many with to-do items, and wanted to re-order the to-do items arbitrarily?
In the past, I've added a numbered order field, and when someone wants to change the order, had to update all the items with their new order numbers. This is probably the worst approach, since it's not atomic & required several updates.
I notice Django has a multi-valued CommaSeparatedIntegerField which could contain the order by storing the ordered keys to the items in the to-do items table right in one field of the project table.
I've pondered a dewey decimal system where if I wanted to take item 3 and put it between 1 and 2 I would change it's order number to 1.5.
Something tells me there's an easier option that I'm missing though...
How would you give order to a one-to-many relationship?
I hate this problem ... and I run into it all the time.
For my most recent Django site we had a Newsletter which contained N Articles and, of course, order was important. I assigned the default order as ascending Article.id, but this failed if Articles were entered in something other than "correct" order.
On the Newsletter change_form.html page I added a little bit of jQuery magic using the Interface plugin (http://interface.eyecon.ro/). I show the titles of the associated Articles and the user can drag them around as they like. There is an onChange handler that recomputes the Article.id's in article_order field.
Enjoy,
Peter
For app=content, model=Newsletter, the following is in
templates/admin/content/newslettter/change_form.html
{% extends 'admin/change_form.html' %}
{% block form_top %}{% endblock %}
{% block extrahead %}{{ block.super }}
<script type="text/javascript" src="/media/js/jquery.js"></script>
<script type="text/javascript" src="/media/js/interface.js"></script>
<script>
$(document).ready(
function () {
$('ol.articles').Sortable(
{
accept : 'sortableitem',
helperclass : 'sorthelper',
activeclass : 'sortableactive',
hoverclass : 'sortablehover',
opacity: 0.8,
fx: 200,
axis: 'vertically',
opacity: 0.4,
revert: true,
trim: 'art_',
onchange:
function(list){
var arts = list[0].o[list[0].id];
var vals = new Array();
var a;
for (a in arts) {
vals[a] = arts[a].replace(/article./, '');
}
$('#id_article_order').attr('value', vals.join(','));
}
});
}
);
</script>
{% endblock %}
{% block after_related_objects %}
{% if original.articles %}
<style>
.sortableitem {
cursor:move;
width: 300px;
list-style-type: none;
}
</style>
<h4>Associated Articles</h4>
<ol class="articles" id="article_list">
{% for art in original.articles %}
<li id="article.{{art.id}}" class="sortableitem">{{art.title}}</li>
{% endfor %}
</ol>
{% endif %}
{% endblock %}
"added a numbered order field" - good.
"update all the items with their new order numbers" - avoidable.
Use numbers with gaps.
Floating point. That way, someone can insert "1.1" between 1 and 2. I find that this works nicely, as most people can understand how the sequencing works. And you don't have to worry too much about how much space to leave -- there's lots and lots of space between each number.
On the initial load, number the articles by the 100 or 1000 or something with space between each one. In this case, you have to guess how many digits to leave for reordering.
A comma-separated position. Initially, they're all (1,0), (2,0), (3,0), etc. But when you want to rearrange things, you might have to introduce (2,1) and (2,2) that go after (2,0) but before (3.0).
This looks kind of complicated, but some people like this kind of complexity. It's essentially the same as floating-point, except the single number is replace by a (whole-number, implicit-fraction) tuple. And this extends to handle hierarchies.
I have had this problem with two projects I've worked on in the last little while. For my example solution I have a "Form" that has many "Variables" assigned to it and the order of the variables on the form needs to be sortable. So I have implemented the following:
models.py
class Form(models.Model):
FormName = models.CharField(verbose_name="Form Name:", max_length=40)
VariableOrder = models.CommaSeparatedIntegerField(default="[]", editable=False)
def __unicode__(self):
return "%s" % (self.FormName)
class Variable(models.Model):
FormID = models.ForeignKey(Form, default=0, editable=False, related_name="Variable")
VarName = models.CharField(max_length=32, verbose_name="Name of variable in the database:")
def __unicode__(self):
return "%s" % self.VarName
The key from above is the VariableOrder CommaSeparatedIntegerField is where we are going to store the order of the Variables on the Form, and we are going to be using it as a python list, which is why the default is [].
For the template I render my Variables in an that we are going to make drag and drop sortable (the list elements I actually use have a ton more CSS related styling and information about the Variable).
<ul id="sortable">
{% for Variable in VarList %}
<li id="{{ Variable.id }}">{{ Variable }}</li>
{% endfor %}
</ul>
Now we are going to make the list drag and drop for the changing of order. For this to work you need to have the AJAX CSRF snippet from Django site in the head
$(function() {
$("#sortable" ).sortable({
placeholder: "ui-state-highlight",
update: function(event, ui){
$.ajax({
type:"POST",
url:"{% url builder.views.variableorder %}",
data: {Order: JSON.stringify($('#sortable').sortable('toArray')) },
success: function(data){
// Do stuff here - I don't do anything.
}
});
}
});
$( "#sortable" ).disableSelection();
});
The important part above is that "update" calls the function every time there is a position change of any of the variables, which sends the AJAX. toArray on sortable along with the JSON stringify gets us sending the top to bottom id's of each variable, which is used by the view as follows. Note: I keep the active Form object as a session variable, but in another case you would just need to call the Form object you were wanting to change the order of.
def variableorder(request):
if request.is_ajax():
Order = request.POST['Order']
updateOrder = request.session['FormID']
updateOrder.VariableOrder = newOrder
updateOrder.save()
request.session['FormID'] = Form.objects.get(id=updateOrder.id)
return HttpResponse("Order changed.")
else:
pass
The key of all of this is that you can use this CommaSeparatedIntegerField as a list by evaluating the string. For example:
Adding a Variable:
aForm = Form.objects.get(id=1)
currentOrder = aForm.VariableOrder
currentOrder = eval(currentOrder)
newVar = Variable(stuff in here)
newVar.save()
currentOrder.append(newVar.id)
aForm.VariableOrder = currentOrder
aForm.save()
Removing a Variable:
aForm = Form.objects.get(id=1)
currentOrder = aForm.VariableOrder
currentOrder = eval(currentOrder)
# Variable ID that we want to delete = 3
currentOrder.remove(3)
aForm.VariableOrder = currentOrder
aForm.save()
Rendering the Variables in Order:
aForm = Form.objects.get(id=1)
currentOrder = aForm.VariableOrder
currentOrder = eval(currentOrder)
VarList = []
for i in currentOrder:
VarList.append(Variable.objects.get(id=i))
This is a rough first draft of what I am going to use, but it is working well for me. The obvious first improvement being the evaluation to python list being a method in the class. eg.
def getVarOrder(self):
return eval(self.VariableOrder)
and then just call Form.getVarOrder() when want to manipulate the list. In any case hopefully this helps out.
JD
I've run into this so many times that I've settled on managing these dynamically in the BL or UI, and then just persisting the ordering to a purpose-built column once the user is happy. SQL is just intentially designed not to handle orderings, and it always fights back.
This is a late answer to the question, but I just wanted to chime in and point out that B-Trees are a great data structure for this sort of thing, especially if your access patterns don't require you to retrieve the entire list at once.
http://en.wikipedia.org/wiki/B-tree