How to add ajax url to js using wp_add_inline_script()?

If anyone still needs it: wp_add_inline_script( ‘map-scripts’, ‘const ajax_info = ‘ . json_encode(array( ‘ajaxurl’ => admin_url(‘admin-ajax.php’), )), ‘before’ ); but, it’s good practice to use nonce as well for better security: wp_add_inline_script( ‘map-scripts’, ‘const ajax_info = ‘ . json_encode(array( ‘ajaxurl’ => admin_url(‘admin-ajax.php’), ‘nonce’ => wp_create_nonce(‘your_nonce_handler’), //the more specific the better ‘your_other_item’ => “some additional data”, … Read more

Problem passing id-specific objects to javascript via wp_localize_script

In your code playerId is a string. So playerId.tracks can’t work. So you can create a multidimensional array with wp_localize_script (WP 3.3+): $playlists = array( ‘playlist150’ => array( ‘tracks’=> array(‘track1’, ‘track2’) ), ‘playlist257’ => array( ‘tracks’=> array(‘track3’, ‘track4’) ) ); wp_localize_script( ‘some_handle’, ‘allPlaylists’, $playlists ); Then in the js use the bracket notation to retrieve … Read more

Update Data parameter of a wp_localize_script() call

wp_localize_script results in your data being printed to the page before your script tag via PHP, whether it be in wp_head or wp_footer, depending on where you’ve set your script to be output. Calling wp_localize_script from an AJAX handler won’t do anything, you’re returning data via JavaScript. What you can do is put any data … Read more

Ajax call with javascript in post content (not enqueued)

If you add the script inline you don’t need to use wp_localize_script. All you have to do is directly print your inline script exactly as you need it dinamically. For example, in your template: <?php // The PHP code of the template here ?> <script> jQuery(document).ready(function($){ var s=1; $(‘button’).on(‘click’,function() { //wfire the ajax call jQuery.ajax({ … Read more

Why is wp_localize_script returning false?

Handle name doesn’t match registered script name in your snippet. wp_enqueue_script has ajax-script and localize has ajax_script notice the dash and underscore. You should also follow example from the docs a. register, b. localise, c. enqueue; like so: <?php // Register the script wp_register_script( ‘some_handle’, ‘path/to/myscript.js’ ); // Localize the script with new data $translation_array … Read more

Path to image in js with wp_localize_script [closed]

Aside from the fact that you shouldn’t use get_bloginfo(‘template_url’), but rather get_template_directory_uri() or it’s *_stylesheet_*() equivalent, it’s a JavaScript problem: The localized object shouldn’t be wrapped in quotes: // Wrong url : ‘svg_path.template_url+”/svg/plus.svg”‘, // Right: url : svg_path.template_url + “/svg/plus.svg”, When handling JavaScript, simply use console.log( svg_path ) in your script to see the output … Read more