Creating a rotating header /image slider using theme customization

We can do that! First, you’ll need to add a custom section on the Theme Customizer, containing all the image uploads (we’ll use 3 for this example):

add_action( 'customize_register', 'themename_customize_register' );
function themename_customize_register($wp_customize) {  

$wp_customize->add_section( 'slides', array(
    'title'          => 'Slides',
    'priority'       => 25,
) );

$wp_customize->add_setting( 'first_slide', array(
    'default'        => '',
) );

$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'first_slide', array(
    'label'   => 'First Slide',
    'section' => 'slides',
    'settings'   => 'first_slide',
) ) );

$wp_customize->add_setting( 'second_slide', array(
    'default'        => '',
) );

$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'second_slide', array(
    'label'   => 'Second Slide',
    'section' => 'slides',
    'settings'   => 'second_slide',
) ) );

$wp_customize->add_setting( 'third_slide', array(
    'default'        => '',
) );

$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'third_slide', array(
    'label'   => 'Third Slide',
    'section' => 'slides',
    'settings'   => 'third_slide',
) ) );
}

Using that code will add a new section, containing 3 file uploads. For now, we’re just using images. Later, you can go back and add descriptions, target URLs, etc. Once you’ve uploaded three slides, all you need to do is call them in your templates.

Calling a theme option is pretty dang easy, using the function get_theme_mod(). To call the first slide, for instance, you just need to use:

echo get_theme_mod('first_slide')

So if you wanted to place a slider on your homepage, for instance, you might open index.php and add some markup like this:

<ul class="slider">
    <li><img src="https://wordpress.stackexchange.com/questions/71404/<?php echo get_theme_mod("first_slide') ?>" height="" width=""></li>
    <li><img src="https://wordpress.stackexchange.com/questions/71404/<?php echo get_theme_mod("second_slide') ?>" height="" width=""></li>
    <li><img src="https://wordpress.stackexchange.com/questions/71404/<?php echo get_theme_mod("third_slide') ?>" height="" width=""></li>
</ul>

Of course, you’ll still need a healthy dose of CSS and JS to make the actual slider, but that’s the basics of uploading, storing, and calling images with the Theme Customizer.

If you’re still a bit hazy, Otto has written a perfect introduction on the rest of the functionality: http://ottopress.com/2012/how-to-leverage-the-theme-customizer-in-your-own-themes/

Leave a Comment