Tutorial: Customizing the WordPress Customizer – Image Uploads to use in your Theme

In the next few days, I am going to post a few code snippets which will help those looking to get started with some simple snippets to get into customising the WordPress Customizer, because there aren’t many specific examples out there on the web about how to achieve certain tasks with what is an often under utilised aspect of WordPress.

Soon, I will add a few discussions of good resources to learn more, but for now, I’m starting with a basic snippet which, when added to Functions.php or your customizer.php file (in the relevant place) will help you to get started when adding an image upload section in order to upload images to be used (somewhere) in your theme.

Step One – Add your Function

function somename_customize_register( $wp_customize ) {
$wp_customize->get_setting( 'image_control_one' )->transport = 'postMessage';
// Add and manipulate theme images to be used.
$wp_customize->add_section('imageoner', array(
"title" => 'Home Page Images',
"priority" => 28,
"description" => __( 'Upload images to display on the homepage.', 'theme-slug' )
));
$wp_customize->add_setting('image_control_one', array(
'default' => '',
'type' => 'theme_mod',
'capability' => 'edit_theme_options',
));
$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'image_control_one', array(
'label' => __( 'Featured Home Page Image One', 'theme-slug' ),
'section' => 'imageoner',
'settings' => 'image_control_one',
))
);
}
add_action( 'customize_register', 'somename_customize_register' );

The above code will add the Section, Setting, and Control necessary to create an image upload.

Step Two – Use this in your Theme File

So the code above will allow you to upload an image into your Customizer to be used in your theme… but where will it go? How will that image be used in the theme?

You need to call your image code into the relevant place in a template, using the following:

echo get_theme_mod('image_control_one');

Now, I use this theme in a CSS style, as a background, so I use the following code (with an override for if there is no image), by doing the following:

if (get_theme_mod('image_control_one') !='') :

Some text here...


Obviously, in real life, we do more things, but this is the basic principle. Note we have not added Sanitize, mime types or etc, because (in this example) we are uploading image files directly. If you need those elements, drop them in.

Recommended:

Leave a comment below if this helped or didn’t help you.

2 thoughts on “Tutorial: Customizing the WordPress Customizer – Image Uploads to use in your Theme”

Leave a comment

No links of any kind allowed in comments - if you add any links, your comment will automatically be deleted.