Enqueue Your Script
wp_localize_script(), we must enqueue our script, with the
<?php wp_enqueue_script( 'my-scripts', get_template_directory_uri() . '/js/my-scripts.js', 'jquery', 1.0, true ); ?>
The first parameter is the name we give our script. The second is the location of our script. This script is in my theme, so I use the
get_template_directory_uri() function, followed by the rest of the path to my script within my theme. The third parameter is the dependency, where I have used jquery as an example (this is the name of the script that this script is dependent on, if there is one). The fourth parameter is the version number of the script, and the fifth is if the script should go in the footer, which I have set to true.
Localize Your Script
Now we can use
wp_localize_script(). Below our enqueue, we add the following:
<?php wp_localize_script( 'my-scripts', 'myScript', array( 'template_url' => get_bloginfo('template_url') ) ); ?>
var url = myScript.template_url+'/path/to/file';
myScript.template_url gives us the path to the theme’s directory, and then we concatenate the rest of the path to the file at the end. This gives us the full URL to the file without hard-coding. For example, this URL could be to a specific image file within your theme.
If you wanted to use the URL to a core WordPress file, for use in Ajax for example, we only need to make a couple simple changes:
<?php wp_localize_script( 'my-scripts', 'wpAjax', array( 'wpurl' => get_bloginfo('wpurl') ) ); ?>
var url = wpAjax.wpurl+'/wp-admin/admin-ajax.php';
wpAjax.wpurl gives us the path to the WordPress directory, and then we concatenate the rest of the path to the core Ajax file.