Adding a Custom Background in WordPress

Now and then you may want to add a background image or a color to the background in a WordPress site. There are a few ways to accomplish this.

The first option that comes to mind is adding a CSS class to the <body> element and then write the styles in a CSS file and enqueue the stylesheet in functions.php files.

Or, you can enable the inbuilt WordPress theme feature custom background using add_theme_support.

Once enabled, the custom background feature allows you to add an image or color to the background of a WordPress site.

As stated earlier, you will need to use add_theme_support function to use this feature.

This is the syntax –

$args = array(
   'default_color' => 'some color',
   'default_image' => 'some image'
add_theme_support( 'custom-background', $args );

You will write this code either in functions.php file in your theme, or if you are writing a custom plugin then this goes to the appropriate plugin file.

After adding the code you will get an option Background from Appearance menu item –

Figure 1

Clicking this option will take you to the background image option in customizer. This is where you can upload an image. There are also options to edit the settings of this image.

Figure 2

You will also get an option to set a Preset or select an image size. Usually I choose fill screen so that the image covers the whole background but you can experiment and change the values to see how it looks like for you.

You can also specify a default_color and a default_image. The default image will show up in the Background Image option and the default color will show up within the Colors option – both in the customizer window.

Figure 3

Remember that, if you fill the screen with background image then the color will not be visible.

Also, the add_theme_support( ‘custom-background’, $args ) is supported from WordPress version 3.4 onwards.