Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

CHAPTER 6 • Advanced Theme Usage 149


CUSTOM BACKGROUND IMAGES


So what about the custom background image? It’s simple: The following code in functions.php
is all you need, preferably used with the after_setup_theme hook as usual:


// Activate the admin panels
add_theme_support( 'custom-background' );


Much like custom headers, there are some default arguments passed here:


$defaults = array(
'default-color' => '',
'default-image' => '',
'wp-head-callback' => '_custom_background_cb',
'admin-head-callback' => '',
'admin-preview-callback' => ''
);
add_theme_support( 'custom-background', $defaults );


Also much like custom headers, this code won’t work with WordPress versions prior to 3.4,
which is worth remembering should you encounter an old and outdated version where the
theme is giving you a headache.


These values are pretty self-explanatory. For your defaults, just pass a color and/or a back-
ground image. The following code sets the background color to a light gray and uses an image
found in the theme’s img folder:


$args = array(
'default-color' => 'bfbfbf',
'default-image' => get_template_directory_uri(). '/img/background.jpg'
);
add_theme_support( 'custom-background', $args );


That’s it! The background settings are attached thanks to the body_class() tag covered
previously, so as long as your theme has one of those, you’ll be fine.


THE THEME CUSTOMIZER AND THEME OPTIONS


The Theme Customizer is a nice feature added in WordPress 3.4. It lets the user tweak
theme settings such as custom headers and custom backgrounds in a user-friendly
interface with a live preview and everything (see Figure 6-5). Just enabling custom
headers and backgrounds and whatnot will add said functionality to the Theme
Customizer, outside of the Title and Tagline settings as well as some readings
settings, but you can extend it even further.

Free download pdf