Backwards compatibility for WordPress 3.4 headers and backgrounds

As I mentioned in the previous post, the new versions of WordPress custom headers and backgrounds have some great new features, but they require WordPress 3.4. That’s no problem if you’re already steering your custom development towards 3.4 (and you should be), but if you’re building themes for distribution, you can’t be sure that all your users are going to upgrade on the first day or even month.

Michael Fields, Automattic Theme Wrangler and all-around smart theme guy, pointed me toward the latest version of P2, which has a rather nice way of handling the backwards compatibility issue for just this case: (This function is called within theme setup)

function p2_setup_custom_header() {
	$args = array(
		'width'               => 980,
		'height'              => 120,
		'default-image'       => '',
		'default-text-color'  => '3478e3',
		'wp-head-callback'    => 'p2_header_style',
		'admin-head-callback' => 'p2_admin_header_style',
	);

	$args = apply_filters( 'p2_custom_header_args', $args );

	if ( function_exists( 'get_custom_header' ) ) {
		add_theme_support( 'custom-header', $args );
	} else {
		// Compat: Versions of WordPress prior to 3.4.
		define( 'HEADER_TEXTCOLOR',    $args['default-text-color'] );
		define( 'HEADER_IMAGE',        $args['default-image'] );
		define( 'HEADER_IMAGE_WIDTH',  $args['width'] );
		define( 'HEADER_IMAGE_HEIGHT', $args['height'] );
		add_custom_image_header( $args['wp-head-callback'], $args['admin-head-callback'] );
	}
}

Elsewhere in the theme setup function, P2 also uses:

	$args = apply_filters( 'p2_custom_background_args', array( 'default-color' => 'f1f1f1' ) );
	if ( function_exists( 'get_custom_header' ) ) {
		add_theme_support( 'custom-background', $args );
	} else {
		// Compat: Versions of WordPress prior to 3.4.
		define( 'BACKGROUND_COLOR', $args['default-color'] );
		add_custom_background();
	}

That’s taken direct from P2 — you’ll have to make adjustments for your own themes: change the slugs, set up the options you want to use, etc.

I can’t think of any reason you couldn’t wrap both function_exists() checks into one conditional, but I’m inclined to keep them separate — it’s easier to read, easier to override in child themes, and if one extra check is a performance concern, it’s time to add a second hamster to your hamster wheel…

(On the other hand, I’m not a fan of holding on to backward compatibility beyond a couple of core versions back. There are a lot of themes out there still checking if widgets are supported, and at that point it’s just cruft. Be nice to your code.)

2 thoughts on “Backwards compatibility for WordPress 3.4 headers and backgrounds

Comments are closed.