Background Images and the Customizer

The WordPress Customizer does not have a built-in control for setting background images. The background feature simply consists of four different controls:

  • background_image (WP_Customize_Background_Image_Control)
  • background_repeat (radio)
  • background_position_x (radio)
  • background_attachment (radio)

For this feature, the Customizer also loads javascript that reveals the radio fields once an image has been uploaded. And on the front-end, inline styles are used to apply the background image to the body tag.

If a developer wanted to build additional background image options, the simplest option would be to take the same route: register four settings, load four controls, add custom javascript to show/hide fields if an image is set. Repeat as needed.

However, I started experimenting with a single control and thinking through how that could be implemented.

Issues with Current Implementation

Trac is a great place to find feedback on a particular WordPress feature, and there were a number of suggestions for background enhancements:

Prior Art

The Make Theme by Theme Foundry implements some of these suggestions, including UI changes:

make-theme

The Kirki Toolkit also implements a background control, which supports repeat, size, attach and position.

Custom Background Control

I haven’t completely finished the custom background control I’ve been working on, but I feel like it’s time to share and open it up for collaboration. Here’s what it does now:

  • A single control generates all the field markup (image, repeat, size, attach, position)
  • The control also saves an attachment ID if a setting is defined (making it easier to generate alternate sizes)
  • The control automatically loads the javascript to hide/show the select fields

At the moment, six settings need to be registered (with their defaults and sanitization) if all the fields are going to be displayed. This still feels like a lot of syntax and I’d like to simplify it further- perhaps by saving all the data into a single serialized array for the theme_mod or option setting that is registered.

It also doesn’t address cropping, alternate UI ideas, or retina- mainly just because I haven’t had a chance to explore it yet. But it does have support background-position-y (added to the position field) and background-size (new select field).

I’d love for other people to take a look at this control and give me any thoughts, feedback, or pull requests. You can find the Custom Background Control on GitHub along with all its documentation.

Check out the project here.

About Devin

I am a developer based in Austin, Texas. I run a little theme shop called DevPress and help manage a WooCommerce shop with Universal Yums. Find me on twitter @devinsays.

Leave a Reply