I’m working on a WordPress theme project where the background needs to change randomly on each page load. To do this I added a body_class that generates a random number between 0 and 5 for me to use for styling (e.g. .random-1, random-2).
Just thought I’d post the snippet in case anyone was looking for something similar:
// Add Random Body Class
add_filter('body_class','random_body_class');
function random_body_class($classes) {
$classes[] = 'random-' . rand(0,5);
return $classes;
}
Note: If you are using a caching plugin like W3 Total Cache, random body classes will be cached and therefore not so random.
Javascript Solution
Here’s a way to do a similar thing with javascript. This would append a random id to your body tag:
<script type="text/javascript">
onload = function() {
document.getElementsByTagName('body')[0].setAttribute('id', 'random-' + Math.floor(Math.random()*7) );
}
</script>
If you change the background so fast you will confuse the users, maybe some way that once a user see a background, it will stick with it ?
That’s not what we were going for with this project, but appreciate the tip.
Wouldn’t this be better accomplished with a little Javascript? You could avoid the page cache problem entirely that way:
$(document).ready(function() {
var rand = Math.floor(Math.random()*11);
$(body).addClass('random-' + rand);
});
Yes, great suggestion. I just added a javascript solution to this post.