How do I conditionally enqueue stylesheets or scripts in theme customizer settings?

I’m developing a new WordPress theme and I’m at the point where I’m adding theme customizer options. Most of them have been surprisingly easy to implement, but I’m stumped on a couple of important options:

  1. Switching between a light and dark theme
  2. Switching between two web font choices

I understand how to properly enqueue stylesheets and scripts and I’m getting pretty familiar with how to add settings, sections and controls to the Theme Customizer. What I need now is a way to conditionally load stylesheets (the light/dark skins) and scripts (the web fonts).

How can I do something like this?

// if the skin is set to 'light'
     // enqueue light.css
// if the skin is set to 'dark'
     // enqueue dark.css

or

// if the font style is set to 'sans-serif'
     // enqueue source-sans-pro;
// if the font-style is set to 'serif'
     // enqueue merriweather;

2 Answers
2

Got it! Here’s the code that worked for me.

— Theme Customizer settings and controls (mine are in a separate customizer.php file):

function themename_customize_register( $wp_customize ) {

    ...

    $wpcustomize->add_setting( 'themename_skin', array(
        'default' => 'light',
        ),
    );

    $wp_customize->add_control( 'themename_skin', array(
        'label'    => 'Skin',
        'section'  => 'colors',
        'settings' => 'themename_skin',
        'type'     => 'radio',
        'choices'  => array(
            'light' => 'Light',
            'dark'  => 'Dark',
            ),
        )
    );

    ...

}

add_action( 'customize_register', 'themename_customize_register' );

— Enqueue the light/dark stylesheets in functions.php along with your other scripts/styles:

function themename_scripts() {

    ...

    /* Enqueue the appropriate CSS based on which skin is selected via Theme Customizer */
    $skin = get_theme_mod( 'themename_skin' );

    if ( $skin == 'light' ) {
        wp_enqueue_style( 'themename-light-skin', get_template_directory_uri() . '/skins/light.css' );
    }
    if ( $skin  == 'dark' ) {
        wp_enqueue_style( 'themename-dark-skin', get_template_directory_uri() . '/skins/dark.css' );
    }

    ...

}

add_action( 'wp_enqueue_scripts', 'themename_scripts' );

Thanks to cale_b for pointing me in the right direction.

Leave a Comment