Hmmm… not using that method, as that will only work on page load. And unless you start storing stuff in the browsers localStorage theres no way to load the next image on refresh and that could hammer your LCP times.
Alternative method.
1. Create a Hook Element
1.1 set the Hook to wp_footer
1.2 Set the Display Rules to the page you want it to apply,
1.3 In the hooks text area add this script:
<script>
window.addEventListener("load", function() {
// set the time delay
const interval = 10000;
// set the number of images to cycle
const maxImages = 3;
var randomNumber = function (min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
};
let root = document.documentElement;
let cnt = randomNumber(1, maxImages);
setInterval(function() {
root.style.setProperty('--hero-bg', "var(--hero-image-" + cnt + ")" );
cnt++;
if (cnt > maxImages) cnt = 1;
}, interval );
});
</script>
<style>
:root {
--hero-bg: var(--hero-fallback);
--hero-fallback: url('url_to_fallback');
--hero-image-1: url('url_to_image_one');
--hero-image-2: url('url_to_image_two');
--hero-image-3: url('url_to_image_three');
}
.page-hero:before{
background-image: var(--hero-bg) !important;
}
</style>
NOTEs: in script
the interval
variable is set to 10000ms
( 10 seconds ) and the maxImages
is 3
Change those to suit.
In the style
change the url_to_*
strings to the the full image url for each of your URLs.