Skip to main content
1 of 3
Milo
  • 78.9k
  • 4
  • 127
  • 168

Enqueue your script and use wp_localize_script to pass data.

function wpd_scripts() {
        
    wp_enqueue_script(
        'wpd_script',
        get_template_directory_uri() . '/js/script.js',
        null,
        null,
        false
    );
    
    wp_localize_script(
        'wpd_script',
        'WPD',
        array(
            'template_dir' => get_template_directory_uri()
        )
    );

}
add_action( 'wp_enqueue_scripts', 'wpd_scripts' );

You can then use WPD.template_dir in your script to get the value you set in PHP.

Milo
  • 78.9k
  • 4
  • 127
  • 168