When wanting to view Shopify collections with varied amounts of products per page (aka, pagination) the usual method involves creating a series of alternate templates. Let's explore an idea that ditches the multiples, and just uses one.
What is this pagination you speak of?
Let's go for some history or backstory first and read up on the proper way you should be doing this:
First, peek at an example on the experiments site.
You'll see the collection template has a dropdown in place (top right) to let you set pagination. Play around with it, view the source, and see if you can figure out what we're doing. Don't worry if you're not sure since we will cover that here.
I think it's pretty cool.
Just how the does magic work?
In a preview post we talked about simple A/B testing using cart attributes to store variables in a server side cookie (of sorts). Since the data is stored server side it means that we can access the values in Liquid!
Since we can see the cart attribute value to a number we will be able to grab that value and apply it directly to our built in pagination code.
Now you'll note that not all code sections below don't exists. Call it clickbait it you like, but the process and example links should still serve as good inspiration. When the project work isn't as pressing I'll jump back to this post and update. For now you'll have to DIY - I'm sure you'll manage! There's also a thread underway on the Shopify forums on the same topic.
[code will be dropped in here. soon...]
So what's the process?
- We first set the default pagination to a known amount (20).
- Check to see if the cart attribute with the name of "pagination" is blank. You can change the attribute name to whatever you want so don't feel compelled to use "pagination" if you don't want to.
- If the attribute isn't blank we will update our paginationAmount variable (via the AJAX API)
- We then use this value in the pagination code.
So if the attribute is blank, use 20. If not, use that saved value. You could paginate with 1 per page all the way to 50 and still only need to use the one template.
- Add a select menu to the page
- Bind a change event to it that fires a function
- The function reads the value (eg: "6") and uses ajax to set the cart attribute
- Once set, reload the page to see it in it's new custom paginated glory.
- Cool thing is all collections will now remember this setting.
If you are dealing with pagination that sets low numbers (so in the 1-5) range be sure to update your design to account for that. The demo store shows how the grid adjusts for the small numbers.