How to Set a Default Custom Background in WordPress 3.0

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 "";
	}
}

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.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie