If you’re a theme developer and you want to allow users to set a custom background image or color, activating the feature in WordPress 3.0 is as simple as including one line of code in your functions.php file. If you want to have a default background image or color, it takes a bit more fiddling around to figure out exactly how to make it work.

I was able to get it working in a couple of my themes so I thought I would share my findings.

Setting up your theme just to use the custom background editor requires this in your functions.php:

if(function_exists('add_custom_background')) {
	add_custom_background('set_theme_background');
}

I like to use the if statement just in case people will be using your theme in an older version of WordPress. Without the if statement, the theme will break. Always think about backwards compatibility if that is important to your theme or to you.

Now, to set a default background, it takes a few more steps. Take a look at the code below:

if(function_exists('add_custom_background')) {
	add_custom_background('set_theme_background');

	function set_theme_background() {
		$bgimage = get_background_image();
		$bgcolor = get_background_color();
		
		echo "<style type='text/css'>\n";
		 
		if(!empty($bgimage)) {
			$background_styles = 'background-image: url(\'' . get_theme_mod('background_image', '') . '\');'
			. ' background-repeat: ' . get_theme_mod('background_repeat', 'repeat') . ';'
			. ' background-position: top ' . get_theme_mod('background_position_x', 'left') .  ';' . 'background-attachment: '. get_theme_mod('background_attachment', 'scroll');
			echo "body { ".$background_styles."); } \n";
		} 
		if(!empty($bgcolor)) {
			echo "body { background-color: #".$bgcolor."; }; \n";
		}
		if(empty($bgimage) && empty($bgcolor)) {
			echo "body { background: url(".THEME_URL."/images/bg.jpg); }\n";
		}
		echo "</style>";
	}
}

This seems a bit sloppy but there are no real functions to gather some of this information so I had to string a lot of things together. What this script is doing, is gathering all the information that could be added by the custom background editor if your user is adding an image or a color. If neither is set, then you can set the default.

My default is an background image called bg.jpg that I have stored in my theme’s /images folder. You can also just set a color, or a large image with no reapeat. It’s totally up to you.