Using wordpress custom fields to control the background.

Read on if you want to change your page background with custom fields.

Screen Shot 2015-06-13 at 10.40.30

Im no developer – but I still do some coding and it is the most fantastic feeling when you get some code working after battling with it for some time. I had an idea to be able from a wordpress post to change the background – dynamically. Setting the background once with a custom field was “easy”. I just used this code in my header (stolen somewhere on the www.) .

 $css = get_post_meta($post->ID, 'css', true);
 if (!empty($css)) { ?>
 <style type="text/css">
 <?php echo $css; ?>
 <?php }

But I wanted to be able to swap it so I found this jquery code I could add in  my page template. Just had to remember to enque jquery in the functions.php.


// alert(backgrounds);

var header = $('body');

var backgrounds = new Array(
 , 'url(http:/'
 , 'url(http:/'
 , 'url(http:/'

var current = 0;


function nextBackground() {
 current = current % backgrounds.length;
 header.css('background-image', backgrounds[current]);
// setInterval(nextBackground, 4000);

header.css('background-image', backgrounds[0]);


So the above code works if you  uncomment the url array. But to be able to change the URLs i could maybe use the custom fields. But grabbing the field keys is done with php and i need to set the jquery array backgrounds to the custom field array. So I found this solution. Use json_encode inside the jquery script to convert the array.

 <?php $songs = get_post_meta($post->ID, 'pattern', false); ?>

var backgrounds = <?php echo json_encode($songs); ?>;

So I also wanted to print links to the images- and I found use of the php substring to cut off unwanted parts. Used inside the html content div.

 <?php $songs = get_post_meta($post->ID, 'pattern', false); ?>

 <h3>Patterns handcrafted by da Hook. Feel free to download and donate:</h3>
 <?php foreach($songs as $song) {
 $songcut = substr($song, 4, -1);
 $songname = substr($song, 37, -1);
 echo '<li><a href="'.$songcut.'">'.$songname.'</a> </li>';
 } ?>

Leave a Reply

Your email address will not be published. Required fields are marked *