Add a random body_class

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>

About Devin

I'm a WordPress developer based in Austin, Texas. Follow my projects on GitHub, or more general WordPress ramblings as @devinsays on twitter.

4 Responses

  1. 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);
    });

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>