How to add support for custom backgrounds in CPTs

Posted on

If you would like to add support for Custom Background Extended in single entries of a Custom Post Type, say WooCommerce products add the following in your child theme’s functions.php:

// add support for custom background to single WooCommerce product pages
add_post_type_support( 'product', 'custom-background' );

Note: If you are using a theme like Agency Pro which uses Backstretch to display the (same) background image site-wide, you have two options for displaying single CPT specific background:

1) To exclude WooCommerce product entries from using the site-wide background image via Backstretch, in functions.php replace

	//* Load scripts only if custom backstretch image is being used
	if ( ! empty( $image ) ) {

		wp_enqueue_script( 'agency-pro-backstretch', get_bloginfo( 'stylesheet_directory' ) . '/js/backstretch.js', array( 'jquery' ), '1.0.0' );
		wp_enqueue_script( 'agency-pro-backstretch-set', get_bloginfo( 'stylesheet_directory' ).'/js/backstretch-set.js' , array( 'jquery', 'agency-pro-backstretch' ), '1.0.0' );

		wp_localize_script( 'agency-pro-backstretch-set', 'BackStretchImg', array( 'src' => str_replace( 'http:', '', $image ) ) );
	
	}

with

	//* Load scripts only if custom backstretch image is being used
	if ( ! empty( $image ) ) {

		if ( is_singular( 'product' ) ) {
			return;
		}

		wp_enqueue_script( 'agency-pro-backstretch', get_bloginfo( 'stylesheet_directory' ) . '/js/backstretch.js', array( 'jquery' ), '1.0.0' );
		wp_enqueue_script( 'agency-pro-backstretch-set', get_bloginfo( 'stylesheet_directory' ).'/js/backstretch-set.js' , array( 'jquery', 'agency-pro-backstretch' ), '1.0.0' );

		wp_localize_script( 'agency-pro-backstretch-set', 'BackStretchImg', array( 'src' => str_replace( 'http:', '', $image ) ) );

	}

Now product-specific background images can be set and the settings in ‘Custom Background’ meta box will work on product pages.

or,

2) To pass the custom background image to Backstretch, in functions.php add

if ( is_singular( 'product' ) ) {
	$image = get_background_image();
}

below

$image = get_option( 'agency-backstretch-image', sprintf( '%s/images/bg.jpg', get_stylesheet_directory_uri() ) );

Now product-specific background images can be set but the settings in ‘Custom Background’ meta box will NOT work on product pages. Instead the image will be shown full screen/stretched via Backstretch.