Day 21: Add Custom WordPress 3 Background Functionality to Your Theme

If you’ve been playing around with the twentyten theme at all you will have noticed that under Appearance you have a new function called Background. From here you can set a background colour or upload a photo to be used as the background, either tiled or by itself. On this 21st Day of WordPress – which happens to be Winter Solstice – I’ll show you how to add this very cool function to other WordPress themes.

Adding the Custom Background function to your theme

The custom background function was introduced in version 3 of WordPress and consists of a single function call placed in functions.php of your theme. It looks like this:


add_custom_background();

Add it to your functions.php file, save the file, upload it to your server and you now have the custom background function. Simple as that.

What does the custom background function do?

When in use the custom background function adds some new style code for the body tag at the very end of the head tag of your pages. This is strictly speaking a bit of a dirty way of achieving the goal, but it works and it is in compliance with web standards. The style code is dynamically created based on how you configure the Background settings and will looks something like this:


<style type="text/css">
body { background-color: #4547de; background-image: url('http://yoursite.com/wp-content/uploads/2010/12/backgroundimage.jpg'); background-repeat: repeat-y; background-position: top left; background-attachment: scroll; }


Because it’s called at the very end of the head of the page it overrides any background image or colour styling in your regular stylesheet.

The background image function is very useful for theme developers because it gives the end user the ability to muck around with the background as much as they want without having to deal with all that pesky CSS code stuff. Nuff said.

This tutorial is part of the 24 Days of WordPress series. If you want to learn more about WordPress and Expression Web check out the Sams Teach Yourself Microsoft Expression Web in 24 Hours series (version 2, 3 and 4), Lynda.com’s WordPress 3.0 Essential Training course and Microsoft Expression Web 4 LiveLessons.