Modify Shopify search - display product variants, correct pagination - shopify

I'm trying to find a way for the following:
I'm modifying a liquid template to also include found product variants on a search result page. But when I do the amount of visible products/product variants on a search results varies greatly and leads to bad UX.
We have a pagination break at 28 items. But this only factors in the amount of products it has already displayed. As I now show variants of the products as well, the pages have a very large amount of items on them. If I decrease the pagination limit to - let's say 4 - I end up with pages that have exactly 4 entries and pages that have let's say 500 entries depending on the matching variations for a given search term.
This is the overall goal:
Display product variants in the search result page as well as the default products and still have a correct pagination that display a fixed amount of products/variants/search result items per page.
My approach was this:
{% capture total_results %}
{%- for result in search.results -%}
{%- case result.object_type -%}
{%- when 'product' -%}
// Go over all the variants and match to the search terms
// Include product-grid-item template in case it matches
{%- when 'article' -%}
{%- when 'page' -%}
{%- endcase -%}
<!-- Divider: #### -->
{%- endfor -%}
{% endcapture %}
{% comment %}Break the captured string at the divider string into an array{% endcomment %}
{%- assign total_results = total_resuls | split: "<!-- Divider: #### -->" -%}
<div class="page__description page__description--centered">
<span>{{ 'search.general.results_count' | t: count: total_results.size, terms: search_terms }}</span>
</div>
{% paginate total_result by 28 %}
{% for result in total_resuls %}
{{ result }}
{% endfor %}
{% endpaginate %}
I get the following liquid error in the frontend: Array 'total_results' is not paginateable.
Is there a way to make it paginateble?
Or is there a way to modify the search.results collection directly so that the pagination doesn't only consider the amount of results from the shopify search but also the variations?
The reason we do this btw is that shopify does seem to find the products based on an information where only the variation matches. But in this case it only links to the product and the user whould need to go to the correct variation manually again which is very bad UX.
Even if the user searches by ID directly they get linked to the normal product page. And we want them to be linked directly to the correct variant that was the reason the product was included in the search results in the first place.
Any help would be appreciated. Or pointers on how else I could achieve this.

Unfortunately, there's no way to paginate through your array. paginate tag can only be used with search.results, collection.products on some other predefined objects.
The way you're trying to implement it doesn't seem possible to me. But here are a couple of ideas came to my mind that might help you:
Option 1. Use search.terms object to build a link to the correct variant. As the main issue is that Shopify search result
links to the product and the user would need to go to the correct variation manually
I would just suggest displaying search results as is but apply your logic from
// Go over all the variants and match to the search terms
to add a ?variant_id=xxx attribute to the search result URL. Then once customers get to the product page, the variant will be selected based on this query parameter. This logic would also perfectly suit the case when customers search by variant ID.
Option 2. Build custom search. It would require more efforts and implies not using the Shopify search at all. You would need to sync store products and return the paginated results from your database based on a query from the search form. This option would give you flexibility in displaying your product results.
I would go with option 1 if the only you want to do is select the correct variant based on the user's search query. But it may not work if you have multiple matching variants and you either want to display all of them separately or be able to redirect the customer to every matching variant from the results page.
P.S. Just a hint: you're using {%- when 'product' -%} block to filter product results only, but you can use ?type=product in your query to search only through products entities, ignoring articles and pages.

Maybe you can try this app https://apps.shopify.com/ultimate-search-and-filter-1 to show variants as separate products on Collection and Search result page without affecting the paginiation in Shopify.

Related

Retrieve all products that contains specific handle in shopify

I want to retrieve list of products that have matching handles.
eg :I have four products having specific words similar in handle
2000-kawasaki-1100-stx-ajpc
2000-kawasaki-1100-stx-kjpc
2000-kawasaki-1100-stx-cpjc
2000-kawasaki-1100-stx-dfgc
Now i want to retrive products that contain 2000-kawasaki-1100-stx in handle.
i tried using
{{ all_products['2000-kawasaki-1100-stx'] }}
But this didnt work ,i cant also loop through all collection because of shopify limit.
Is there any way to get this work ?
as you say, the all_products object has a limit of 20 unique handles per page. If you want more than 20 products, then consider using a collection instead.
An example collection iteration:
{% for product in collections.all.products %}
{%- case product.id -%}
{%- when '123456' -%}
{% assign my_product = product %}
{% endcasae %}
{% endfor %}
instead of using "if" please use "case" so best code practice and fast result while searching on loop of around 50 iterations.

Empty spaces in filtered list

I am trying to return a list of all product IDs which contain 'sometag' in Shopify to power a theme section I'm building.
At first I was stuck by the limit of 50 products in a query (my catalogue is 600+ products), but by adding pagination to my for loop I have been able to return a filtered list from a collection containing all products to show only the tagged products I'm looking for.
However, despite the filtered list usually only containing around 1-5 items depending on tag, Shopify is still displaying the full pagination list for the entire product library - only every page is empty apart from the filtered items (which are usually on page 3 or 4 or something) - so it's not really removing the filtered out items, rather not displaying them and leaving their index spaces there empty.
Does anyone have any advice on how to trim out all the blank entries from the returned list and only display the filtered results?
{% paginate collections['somecollection'].products by 50 %}
{% for product in collections['somecollection'].products %}
{%- if product.tags contains 'sometag' -%}
{{ product.id }}
{% endif %}
{% endfor %}
{{ paginate | default_pagination }}
{% endpaginate %}
EDIT: Shopify tell me this is 'expected behavior' so I guess I need to create some mini app or use JS or something.
Because Liquid pagination happens server-side, it will always be based on the actual size of the collection, not on a sorted subset created for front end display.

Getting all products in shopify that do not contain a tag

I am using bundle builder app that lets users create their own bundles and purchase them. With each purchase it creates a product variation. When there are over 99 variations the app duplicates the bundle product and repeats itself till infinity. The problem here is that the old product bundles are no longer valid but still show in the front end causing confusion. I was able to bug bundle builder app support enough to provide me with info on how to detect these legacy products so we can hide these products from the collections page like so:
{%- for product in collection.products -%}
{%- if product.tags contains 'bundle-builder-dummy-legacy' -%}
** do nothing **
{%- else -%}
** print out product **
{%- endif -%}
{%- endfor -%}
Now this hides the legacy products but it still messes up the pagination and the page layout, for example our page limit is set to 8 products, we are on page 2 of 5. Using the above code snippet prints out only the products that do not contain the tag 'bundle-builder-dummy-legacy' (this could be improved with unless statement, but that is not the point), but it leaves empty space - only 6 grid items are filled instead of 8. So I guess the for loop is not working correctly. How can I get the products inside the for loop that do not contain the tag. Meaning an if/unless statement need to happen before the loop or during loop init. Hope I've made clear of the situation I have.
Thanks
What you might do is asking app to identify those products using a directly accessible attribute of the product, like type.
Then you would be able to do this:
{% assign collection_products = collection.products | where:'type','legacy' %}
{% for product in collection_products %}
Do something
{% endfor %}

Show products on article

How can I show a list of products (like a recipe) on a article page.
Can you give me some guidance on what should i use to achieve that behavior?
How can i link those products dynamically to the article?
Getting the products once we know what they are
There are two ways to bring up products on an arbitrary page in Shopify:
1) Using all_products[handle]
Using the product handle to get the product from the all_products global object.
Example:
{% assign ingredient = all_products['lavender-oil'] %}
This works well for small numbers of products, but for large numbers of products it may cause delays in page-loading times. We are also limited to only 20 (I think) calls to all_products per page, so this wouldn't work for recipes with a ton of ingredients in them.
2) Using a collection
Use a collection that contains only the products required. You can reference any arbitrary collection if you know the collection's handle. When making collections, you can also sort products manually to control the order that they appear in when you loop through it. Collections can contain an arbitrary number of products, and I believe the default pagination will give you is either the first 20 or 50 products if you don't specify any other limit. If required you can adjust the number of products served to as high as 1000 by wrapping your collection-product loop with paginate tags (though that upper limit is definitely not recommended for performance reasons)
Example:
{% assign ingredients = collections['love-potion-number-9'] %}
{% for product in ingredients.products %}
<h2>{{ product.name }}!!</h2>
{% endfor %}
The downside for both of these is that you can't write Liquid code inside your article content in Shopify, so this ingredients section would need to be written as a snippet or a section in your theme files and included in your article template used for these recipes.
This leads me to consider the next issue - you would want to include a concept of quantity with the ingredients, and so far neither of the above give us that. So now, the hard part:
Getting that information into a Liquid snippet/section in the first place
There are a few different ways that I can think of offhand that would help you out here. No one is perfect, unfortunately.
Using Metafields
Metafields are a great tool available in Shopify, but unfortunately Shopify doesn't make them easy to use [1].
Once you have a metafield-editing tool, come up with a naming structure for the 'namespace' and 'key' values. For example, you might create the following metafields for the recipe you provided. (Note: How these would be entered will depend on what metafield-editing tool you're using)
namespace: 'ingredients', // We'll use this as the 'box' that holds all our ingredients
key: 'juniper-berry-oil', // This will be the product handle for the product in question
value: '2 drops' // The quantity used for the recipe
namespace: 'ingredients',
key: 'rosemary-ct-camphor-oil',
value: '1 drop'
namespace: 'ingredients',
key: 'cypress-oil',
value: '1 drop'
... (etc) ...
Then, in your theme file where you are creating your ingredient list, you would have code that looks something like this:
{% assign ingredients = article.metafields.ingredients %}
{% for ingredient in ingredients %}
{% assign handle = ingredient.first %}
{% assign amount = ingredient.last %}
{% assign product = all_products[handle] %}
<!-- HTML code here -->
{% endfor %}
Using Tags and Products
If you create a tag-naming scheme, you can loop through those and use them to build your ingredient list. For example, if you give the article a number of tags in the form ingredient_[product-handle]_[amount], you would be able to reference them as:
{% for tag in article.tags %}
{% if tag contains 'ingredient' %}
{% assign breakdown = tag | split: '_' %}
{% assign handle = breakdown[1] %}
{% assign product = all_products[handle] %}
{% assign amount = breakdown | last %}
<!-- HTML Code -->
{% endif %}
{% endfor %}
The downside to this method is that there's no easy way to reorder the tags if done this way - using a collection will give you better control of that.
Getting recipe amounts into a Collection loop
The easiest way to reference a collection would be to have a collection with the same handle as the article - then you can reference the collection and its products as:
{% assign ingredients = collections[article.handle] %}
{% for product in ingredients.products %}
<!-- HTML Code here -->
{% endfor %}
This has the advantage of letting you easily sort the ingredients by setting the collection to have a Manual sorting method, but the corresponding downside is that there's no obvious place to put the quantity information.
One way to get that information in would be to use either tags or metafields - metafields would have the advantage of being able to directly access the quantity for the product - if using the naming convention above in the metafields part of this answer, you could use:
{% assign ingredients = collections[article.handle] %}
{% for product in ingredients.products %}
{% assign amount = article.metafields.ingredients[product.handle] %}
<!-- HTML Code here -->
{% endfor %}
If using tags, you would need a format that could be split up like in the tag section and loop through all your tags each time to find the one for your product. If your tags were set up as ingredient_[product-handle]_[amount]
If using tags, you would need a format that could be split up like in the tag section and loop through all your tags each time to find the one for your product. If your tags were set up as the example above:
{% for tag in article.tags %}
{% if tag contains 'ingredient' and tag contains product.handle %}
{% assign amount = tag | split: '_' | last %}
{% endif %}
<!-- HTML Code -->
{% endfor %}
Hopefully this helps you get going!
[1] Using Metafields: There are several possible solutions for editing metafields in Shopify - my personal preference is the 'Shopify FD' extension for Chrome, but the recent updates to the Shopify admin screens are interfering with this extension's ability to load & show its metafield panels on some pages. I know that product pages still work, but some pages (like collections) don't anymore.
There are also a number of apps available for your store to edit metafields - I haven't used any of them, so I can't speak to their value, but you can view the list here: https://apps.shopify.com/search?q=metafield&st_source=
If you have a coding background, you can also create and update metafields yourself by sending the right data to Shopify's Admin API - see the documentation at https://help.shopify.com/en/api/reference/metafield if you want to try doing it yourself.
Here is a sure to succeed recipe. Write your Article. It will have a handle, unique to it. Save that in your head, clipboard, etc. Now create a manual collection. Give it the same handle. Now you can reference an empty collection by the Liquid:
collection['some-handle-to-an-article']
What if you now filled that collection with the products in your recipe? Eureka. Genial! You can then list them in a simple Liquid for next loop like this:
{% for product in collection['some-handle-to-an-article'] %}
{{ product.title }}
{% endfor %}
Or you could be a smarty pants and gather the handles of the products manually yourself. Store them in a metafield resource assigned to the article. For example, a string like 'a-blah,b-blahblah,c-zigo-von-goober' and then use Liquid to find that metafield in the article template. Split that string by commas. Now use the most excellent all_products like this:
{% assign fizzbuzz = all_products['a-blah'] %}
{{ fizzbuzz.title }}
And there are many more creative options. Shopify Liquid is ripe for play like this. No limits, except on all_products at 20... you cannot go more than that.

Shopify(Liquid) multiple conditions in if statement

I am looping through all collections, and creating a preview item with each collection title, image and link. But I have 15 collections I would like to exclude.
Currently I am using 'contains' to exclude the 15 I don't want, but am wondering if theres a cleaner way to write this since its a really long if condition.
Thanks in advance!
Example below:
{% for collection in collections %}
{% if collection.title contains 'collection-1' or collection.title
contains 'collection-2' or collection.title contains 'collection-3'
or collection.title contains 'collection-4' or collection.title
contains 'collection-5' %}
{% else %}
// build item here
{% endif %}
{% endfor %}
I would create an array of exclusions and check to see if my exclusion array contains the collection in question. (And rather than the title, I would use the collection handle as the handle is guaranteed to only be 'clean' names and guaranteed to be unique)
Example:
{% assign collection_exclusion_array = 'collection-1, collection-2, collection-3, collection-4, collection-5' | remove: ' ' | split: ',' %}
{% for collection in collections %}
{% if collection_exclusion_array contains collection.handle %}
{% continue %}
{% endif %}
{% comment %} Build items here {% endcomment %}
{% endfor %}
How it works:
We cannot directly create arrays in Liquid - we can only make one by taking a string and using the split filter to create our array.
By using handles, we guarantee that our list values only contains letters, numbers and hyphens - there's no chance that our delimiter (in this case, the comma) can accidentally show up as part of the value.
We don't want spaces to be part of the array values, so we remove them before we use the split filter. We could instead just not put spaces between each value, but in my brain that reads like a terrible abuse of grammar. Either omitting spaces the first time or removing them after creating your string will work.
Now that we have our array of exclusions, when we loop through collections we can check to see if the current collection's handle shows up in the list.
If found, skip to the next collection using the continue statement - this saves a layer of indentation since we don't have to have an empty if followed by an else that contains everything that we want to do.
And there you go! Hope it helps :)
NB: For more information on handles in Shopify, see https://help.shopify.com/en/themes/liquid/basics/handle
An alternate method to achieve your exclusions:
If you give your collections some sort of flag that indicates that they shouldn't show up in your collection loop, you can manage each collection directly, rather than maintaining a separate list.
If we look at the collection page in your admin, though, we don't get a lot that's helpful: all we see are things like title, description, etc. Not even a place to give the collection a specific tag!
Fortunately, collections are able to have metafields - Shopify just has that feature hidden from normal users. Metafields allow you to create additional information for objects in your store (products, collections, pages, etc.), which you can then reference through Liquid.
You can read more about Shopify's use of metafields here: https://www.shopify.com/partners/blog/110057030-using-metafields-in-your-shopify-theme
My previous favourite plugin for accessing metafields was ShopifyFD, a browser extension that would let you view and edit that metadata right on your collection page, but unfortunately Shopify's recent changes to the admin have broken that plugin. The author is working on a new version, but it's not ready at the time of writing: https://freakdesign.com.au/blogs/news/shopifyfd-and-the-current-case-of-the-broken-tool
(Note: I haven't tried any of the other metafield-editing tools listed in the above linked article - when ShopifyFD started having trouble, I started doing my metafield editing using the admin API and creating/posting the requests myself: https://help.shopify.com/en/api/reference/metafield)
Once you have a way to easily set metafields (which, surprisingly, seems to be the hard part right now), your for-loop logic is extremely simple. Let's assume that the metafield you create for this purpose has the namespace 'preview' and the key 'exclude':
{% for collection in collections %}
{% if collection.metafields.preview.exclude %}
{% continue %}
{% endif %}
{% comment %} Do stuff! {% endcomment %}
{% endfor %}
This will now skip any collection that has any value set in your custom field, so if you change your mind about any current or future collection all that needs to change is the one metafield on the collection itself.