WordPress Custom Theme: mixing php and javaScript?

Solution:1

The “WordPress way” would be to localize the script.

Utilize wp_localize_script

Overview:

  1. Register a script in your theme (usually in your functions.php file). See here: wp_enqueue_script
  2. Localize the script
  3. Then, access that value via your javascript.

Minimal complete example (compiled from WP docs):

PHP:

add_action('wp_enqueue_scripts', 'my_theme_scripts');

function my_theme_scripts() {
    // Register the script first.
    wp_register_script( 'some_handle', 'path/to/myscript.js' );

    // Now we can localize the script with our data.
    $color_array = array( 'color1' => get_theme_mod('color1'), 'color2' => '#000099' );
    wp_localize_script( 'some_handle', 'object_name', $color_array );

    // The script can be enqueued now or later.
    wp_enqueue_script( 'some_handle' );
}

Javascript (in your ‘myscript.js’ file);

// Access the color via the object name defined in localize_script
var color = object_name.color1;

Solution:2

It is at times necessary to do this in your theme. For this WordPress has provided us with wp_localize_script function. The benefit of using this function is that you don’t have to enqueue anything in the header.php.

Add this to your functions file:

wp_enqueue_script( 'my_js_library', get_template_directory_uri().'/js/myLibrary.js' );

$dataToBePassed = array(
     'bandname'            => get_current_user_id(),
);
wp_localize_script( 'my_js_library', 'php_vars', $datatoBePassed );

You can use the value of wp_localize_script function in the my_js_library.js file.