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

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) );

About Devin

I'm a WordPress developer based in Austin, Texas. I work with the fantastic crew at 10up and also run a little theme shop called DevPress. Find me on twitter @devinsays.

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