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

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