I’m trying to show random images/video in product category pages. Every category page will display their own set of images.
I did it in the typical rookie way by adding in every product category page with their own respective set of images. Is there a way that I can use hooks to do it at functions.php for ease of maintenance?
var total_images = 7;
var image1 = document.getElementById('banner1');
var image2 = document.getElementById('banner2');
var image3 = document.getElementById('banner3');
var random_numbers = [];
var random_number;
var random_img = [];
random_img[0] = '<a href="banner1.jpeg"><img src="banner1.jpeg"></a>';
random_img[1] = '<a href="banner2.jpeg"><img src="banner2.jpeg"></a>';
random_img[2] = '<a href="banner3.jpeg"><img src="banner3.jpeg"></a>';
random_img[3] = '<a href="banner4.jpeg"><img src="banner4.jpeg"></a>';
random_img[4] = '<a href="banner5.jpeg"><img src="banner5.jpeg"></a>';
random_img[5] = '<a href="banner6.jpeg"><img src="banner6.jpeg"></a>';
random_img[6] = '<a href="banner7.jpeg"><img src="banner7.jpeg"></a>';
while(random_numbers.length < 3){
random_number = Math.floor((Math.random() * total_images));
if(random_numbers.indexOf(random_number) < 0){
random_numbers.push(random_number);
}
}
image1.innerHTML = random_img[random_numbers[0]];
image2.innerHTML = random_img[random_numbers[1]];
image3.innerHTML = random_img[random_numbers[2]];
2
Answers
I have developed something similar in the past, but not in javascript, it was all php code.
I had added a new banner field in the categories with ACF (only one, you would have many), and then on the category page I would show that banner or, recursively, the father’s banner, until I found one.
You would have multiple image fields, and you would extract one at random, maybe it can be useful to you.
In any case, the hook to use is: woocommerce_before_main_content action.
If you want to use javascript instead, you have to add it in your js file in the child theme, and call the script for example like this:
The easy way – Install ACF plugin and create your fields – https://prnt.sc/1yek9zy .
For image field select image url. Duplucate Banner 1 as many banners you want and setup Location rules to taxonomy product category – https://prnt.sc/1yekgys
Then go to a product category and add your images and urls – https://prnt.sc/1yeklpf
If you have ACF pro go with repeater field instead. Its more dynamic and you can add as many banners you want per product category.
Use this visual hook guide to change where you want the banners to be showed – https://www.businessbloomer.com/woocommerce-visual-hook-guide-archiveshopcat-page/