How do I pass the template url to javascript in the ADMIN area of my theme?

If you want to use the variables from the admin.js script, and you want to be sure it works you have to use as handle for wp_localize_script the handle of the script that have to use data call wp_localize_script after that script is enqueued wp_enqueue_script( ‘some_handle’ ); wp_enqueue_script(“admin”, $adminDir.”js/admin.js”, false, “1.0”); $translation_array = array( ‘some_string’ … Read more

Localization of JavaScript which is only used in one page

You can add conditional statements inside the wp_enqueue_scripts action hook. add_action( ‘wp_enqueue_scripts’, function() { if( is_page( ‘page-slug’ ) ) { // Enqueued script with localized data. wp_enqueue_script( ‘register-validation-js’ ); } } ); You can refer to the is_page documentation for more information on what arguments can be pass.

How to get the post ID when creating JS variables with localize_script

You should declare global $post; before attempting to access this variable, but to answer your question regarding when it is created, the ‘wp’ action hook is the safest bet. As such I’d suggest the following in your functions.php file as a simple solution function my_localize_post_id(){ global $post; wp_register_script( ‘your_script’… /** other parameters required here **/ … Read more

How do you pass a boolean value to wp_localize_script [duplicate]

Unfortunately wp_localize_script() casts all scalars (simple types) in the passed-in array to strings (and then runs html_entity_decode() on them?!), so the casts mentioned by the answer you quote & @TheDeadMedic will get stringified “1”https://wordpress.stackexchange.com/”” if boolean, and number strings if ints, which won’t work with javascript plugins that demand exact values. A way around it … Read more

Use wp_localize_script for non existing script

How does core do it? After thinking again about it, I thought there might be a case where WP does the same thing internally. And right: It does it. Example ~/wp-admin/load-scripts.php $wp_scripts = new WP_Scripts(); wp_default_scripts($wp_scripts); // inside wp_default_scripts( &$scripts ) $scripts->add( $handle, $src, $dependencies, $version, $args ); // from WP_Dependencies $scripts->localize( $handle, $object_name, $data … Read more

wp_localized_script is not defined when called via jquey ajax

To successfully add variable to the window object via wp_localize_script you need to properly invoke three functions in the following sequence: wp_register_script wp_localize_script wp_enqueue_script In your case you’re missing the wp_register_script. In case someone experiences the same issue, follow the code procedures below. PHP <?php function my_theme_wp_enqueue_scripts() { $handle=”my_handle”; // Register the script wp_register_script($handle, ‘/path/to/my_script.js’); … Read more