I am trying to use the WordPress path URL in my js script file. I read here that I need to use wp_localize_script
. But, I according to Codex's documentation
wp_localize_script() MUST be called after the script has been registered using wp_register_script() or wp_enqueue_script()
How can I do that?
This is my function
if(!function_exists('pt_scripts')):
function pt_scripts () {
wp_register_style( 'style', get_stylesheet_uri(), null, '1.3.1', 'all');
wp_enqueue_style( 'style');
wp_register_script( 'scripts', get_template_directory_uri() . '/script.js', array('jquery'), '1.3.0', true );
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'scripts' );
}
endif;
add_action('wp_enqueue_scripts','pt_scripts');
Thank you very much.
I am trying to use the WordPress path URL in my js script file. I read here that I need to use wp_localize_script
. But, I according to Codex's documentation
wp_localize_script() MUST be called after the script has been registered using wp_register_script() or wp_enqueue_script()
How can I do that?
This is my function
if(!function_exists('pt_scripts')):
function pt_scripts () {
wp_register_style( 'style', get_stylesheet_uri(), null, '1.3.1', 'all');
wp_enqueue_style( 'style');
wp_register_script( 'scripts', get_template_directory_uri() . '/script.js', array('jquery'), '1.3.0', true );
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'scripts' );
}
endif;
add_action('wp_enqueue_scripts','pt_scripts');
Thank you very much.
Well, you have to call wp_licalize_script
after registering the script, because you need handle of that script... And of course you can't localize something that doesn't exist...
Here's some example:
if ( !function_exists('pt_scripts') ):
function pt_scripts () {
wp_register_style( 'style', get_stylesheet_uri(), null, '1.3.1', 'all' );
wp_enqueue_style( 'style' );
wp_register_script( 'scripts', get_template_directory_uri() . '/script.js', array('jquery'), '1.3.0', true );
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'scripts' );
wp_localize_script( 'scripts', 'ScriptsData', array(
'some_data_1' => 'data1',
...
) ); // 'ScriptsData' is name of object that you can access in your JS
}
endif;
add_action( 'wp_enqueue_scripts', 'pt_scripts' );
PS. 'scripts
' is not the best name for script handle - it's pretty easy to get some conflicts with such names.
'scripts'
on the 3rd and 5th line of your function respectively, so you just need to usewp_localize_script()
after those lines. – Jacob Peattie Commented Sep 7, 2018 at 5:11