Our journey starts here
with the WP_Customize_Background_Image_Control
class, which is a WP_Customize_Image_Control
.
I’d imagine offering these built-in backgrounds in a new tab alongside the existing Upload New
and Uploaded
tabs. There are at least two ways of achieving the following: either creating your own modified class based off of the WP_Customize_Background_Image_Control
class, or altering its default behavior by hijacking the global $wp_customize
instead. The former is the longer way (albeit perhaps cleaner), wherein we would first of all we have to define our new control:
class WP_Customize_Background_Image_Control_Defaults extends WP_Customize_Background_Image_Control {
public function __construct( $manager ) {
...
$this->add_tab( 'builtins', __('Built-ins'), array( $this, 'tab_builtins' ) );
...
public function tab_builtins() {
...
}
Then remove the default background image control that was registered by default and add our own new class:
add_action( 'customize_register', function( $wp_customize ) {
/* Substitute the default control for our new one */
$wp_customize->remove_control( 'background_image' );
$wp_customize->add_control( new WP_Customize_Background_Image_Control_Defaults( $wp_customize ) );
}, 11, 1 );
The new tab would then simply echo out a set of predefined images that are shipped with your theme, akin to how the default tab_uploaded
functions with minor adjustments. This function would be the same for either when you’re using a custom class, or trying out the faster approach.
The faster, more compact approach involves making the default control dance to our tune after initialization like so:
add_action( 'customize_register', function( $wp_customize ) {
$control = $wp_customize->get_control( 'background_image' );
$control->add_tab( 'builtins', __('Built-ins'), function() {
/* Supply a list of built-in background that come with your theme */
$backgrounds = array(
'images/bg-01.png', 'images/bg-02.png', ...
);
global $wp_customize;
$control = $wp_customize->get_control( 'background_image' );
foreach ( (array) $backgrounds as $background )
$control->print_tab_image( esc_url_raw( get_stylesheet_directory_uri() . "https://wordpress.stackexchange.com/" . $background ) );
} );
}, 11, 1 );
Again, if you choose to use your own class, you’d do pretty much the same, add_tab
which does a print_tab_image
on all your preset backgrounds. Pretty straightforward. I’m sure you can further improve the code with various odds and ends, but overall this looks like the way to go I think.
Questions, ideas, thoughts welcome.