How to Set Default CSS Background Properties in WordPress Themes

Here’s a handy trick for WordPress theme developers. As of WordPress 3.8, theme authors have the ability to customize defaults when adding custom background support. For example, you can set a default for any of the following CSS background properties:

  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position

Oftentimes users want their sites to look similar to the demo, but they may be unaware of how to adjust the background properties to achieve that. It’s nice to have some defaults in place so that the theme looks similar to the demo right out of the box, without any adjustments.

Depending on the background image that you select, it can be advantageous to set its defaults to the most sensible display for that image. For example, if your default background is an image that’s meant to tile, you want it displayed like that after the user activates the theme.

Adding custom background support to the customizer is done through your theme’s functions.php file:

add_theme_support( 'custom-background' );

From here you can further customize the background properties by adding default arguments. Usually themes add custom background support to a setup function with other customizer options. Here’s a quick example of setting a default background to no-repeat, centered position with fixed attachment.

function yourtheme_setup() {
	add_theme_support(
		'custom-background',
		array(
			'default-color' => '2d2d2d',
			'default-image' => get_template_directory_uri() . '/images/background.jpg',
			'default-repeat'     => 'no-repeat',
			'default-position-x' => 'center',
			'default-attachment' => 'fixed',

		)
	);
}
add_action( 'after_setup_theme', 'yourtheme_setup' );

Here’s what that looks like in the customizer by default after the user installs the new theme:

background-customizer

Of course, the user can still adjust these properties through the customizer to suit their own custom background images. The defaults simply ensure that the packaged background image looks nice when the theme is activated for the first time.

Who is Sarah Gooding


Sarah Gooding is an Editorial Ninja at Audrey Capital. When not writing about WordPress, she enjoys baking, knitting, judging beer competitions and spending time with her Italian Greyhound.

There are 2 comments

Comments are closed.