JavaScript in WordPress Customizer

Customizer Codes:

$wp_customize->add_setting (
    'script-code',
    array (
        'default' => esc_html__( 'Script Code', 'x' ),
        'sanitize_callback' => 'wp_kses_post'
    )
);

$wp_customize->add_control (
    new WP_Customize_Control (
        $wp_customize,
        'script-code',
        array (
            'label' => esc_html__( 'Script Code', 'x' ),
            'section' => 'script',
            'settings' => 'script-code',
            'type' => 'textarea',
            'priority' => 1
        )
    )
);

Photo from Customizer:

enter image description here

from codes for output:

<?php echo wp_kses_post(get_theme_mod('script-code')); ?>

from output, return the empty:

<main class="script-code">
</main>

How can I use script tag in Customizer textarea setting field ?

Thanks so much.

1 Answer
1

This is because you are using wp_kses_post to sanitize the output data, try without it:

<?php echo get_theme_mod( 'script-code'); ?>

also remove it from here:

$wp_customize->add_setting (
    'script-code',
    array (
        'default' => esc_html__( 'Script Code', 'x' ),
        'sanitize_callback' => '' // remove wp_kses_post
    )
); 

also make sure you are using the right name of your theme mod you can check that in two ways:

1.- do a var_dump(get_theme_mods()); check there how is named.

2.- Inspect the HTML code of your control in the customizer

enter image description here

the id without the prefix customize-control- is the name of your theme mod.

Leave a Comment