Hello all. I just wanted to share something I worked up to solve a need for random background images on the home page of a site I'm working on. (I'll post the URL of the site when we launch).
I was unable to find a workaround or get assistance from Shopify regarding the fact the Liquid appears to cache it's output so when you try to randomize a number it hangs on to the number it first outputs until you clear your cache and hard refresh. (Note: I'm open to any and all recommendations about how to work around this or how to streamline what I've done here. I'm really happy with how it works now and hopefully, it will help some of you out there too.
Here's where I landed:
This took me far longer than I had anticipated so I wanted to share.
Here is the code for the whole 'sections/home-background_images.liquid' file:
All other ways are just funky hacks like just putting the random seed in the url, which means it's not really random either.
l will certainly try...
Once you have your Background Image schema set up you are able to retrieve the block settings 'size' which is the total number of images that have been added to your page.
You use that number to randomize a number between 1 and the total number of images. Then you use the number selected to output that image as your background.
The code I provided should work well if you want to try it. The images are added in the Shopify Admin when you go into customize/edit your homepage.
|an hour ago|
|an hour ago|