22

Instead of using wp_localize_script in that case, you can hook your js variables at wp_head, that way it would be available to all js files like: function my_js_variables(){ ?> <script type="text/javascript"> var ajaxurl = '<?php echo admin_url( "admin-ajax.php" ); ?>'; var ajaxnonce = '<?php echo wp_create_nonce( "...


12

You can export any data you want in the wp_head hook, as the answers above show. However, you should use json_encode to prepare the PHP data for exporting to JS instead of trying to embed raw values into JS literals: function my_js_variables(){ ?> <script> var ajaxurl = <?php echo json_encode( admin_url( "admin-ajax.php" ) ) ?>; ...


9

wp_localize_script() calls the method localize() on the global variable $wp_scripts. We can set this variable to an instance of a child class of WP_Scripts: class Filterable_Scripts extends WP_Scripts { function localize( $handle, $object_name, $l10n ) { $l10n = apply_filters( 'script_l10n', $l10n, $handle, $object_name ); return ...


9

You can simply put your init code within the constructor of the class. For example: class myWidget extends WP_Widget{ function myWidget(){ // Init code here } function widget( $args, $instance ) { // The widget code wp_enqueue_script(...); wp_enqueue_style(...); } // Over methods... } register_widget('...


6

This will be possible in WP 3.3: http://core.trac.wordpress.org/changeset/18480


6

wp_localize_script takes an array of data (in PHP) spits out a javascript. It's a way for you to add dynamic data for a specific script to the front end without having to hook into wp_head or wp_footer and echo it out yourself. More over, wp_localize_script outputs your data right above the script you enqueued. Hooking into wp_head or wp_footer won't do ...


6

TL;DR There is no JavaScript API in the WordPress core and no one is planned, but actually, there is no need of it. Backend First of all let's say that, regarding the backend, some useful information can be fetched from already present JavaScript global variables (WordPress loves all global flavors). E.g. ajaxurl for the admin-ajax.php url to be used ...


5

Your code is PHP4 style. PHP4 styled code should not be used anymore. And just putting some functions inside a class construct is not OOP. If you want to write reusable code, separate your code. For example: class Widget_Setup { public $widget_class = ''; public $admin_styles = array(); public $admin_scripts = array(); public $...


5

W3 Total Cache has 4 locations to include the minified files. Since wp_localize_script() hooks into wp_head() (unless you specify in footer in your enqueue) you can use the before </body> minify location and your script will have access to the variables set. On some occasions this has failed for me so I just exclude the script from minify.


5

There're easier ways than this. As @Wyck already stated that using globals is bad idea, here's a short explanation and how to: Why globals are bad: 1) Everyone can access them everywhere. First this sounds nice, but you can as well do the following: // Your code: default value global $foo; $foo = 'bar'; // User setting: global $foo; $foo = get_option( '...


5

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"/"" if boolean, and number strings if ints, which won't work with javascript plugins that demand exact values. A way ...


4

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 ...


4

You should be setting it to show in the footer with the register, so your code should look like this: wp_register_script( 'flowplayer_object', get_bloginfo( 'stylesheet_directory' ) . '/_/js/flowplayer/flowplayer-object-creator.js', array(), // these are your dependencies, if you need jQuery or something, it needs to go in that array false, /...


4

I tested that code like this: wp_enqueue_script('jquery'); wp_localize_script( 'jquery', 'MS_Ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'nextNonce' => wp_create_nonce( 'myajax-next-nonce' )) ); And it works but throws a Notice. It should be hooked to wp_enqueue_scripts like: function my_enqueue_scripts() { ...


4

Try this: $options = get_option( 'theme' ); wp_localize_script( 'flexslider', 'flex_vars', array ( 'flex_auto' => ($options['slide-auto']) ? 'true' : 'false', 'flex_animation' => $options['slide-animation'], 'flex_direction' => $options['slide-direction'] ) ); Assuming slide-auto is the option you made a boolean. This script isn't tested, ...


4

You have to use the correct handle: wp_localize_script('page_data', 'glr_dt', $gallery_js_data_array); // Edit Your code is also wrong. What do you want to do in this line: 'maxPages' => '$gallery_max_load = $gallery->max_num_pages;' You are assigning a string to maxPages. I guess you want it that way (or similar): 'maxPages' => $gallery->...


4

I am not a jQuery expert, but I ran into the same problem and I believe I have a workable solution. The problem is that each time you run wp_localize_script it creates a javascript variable using the $name setting. In your case that is 'carouselvars'. As this is set before the jQuery in run, only the last values passed to the variable are 'seen' by jQuery, ...


4

There has been quite a bit of development around the JSON REST API that is supposed to be merged into the 4.1 release. I believe it's officially going to be called the 'WP API'. You can begin using the codebase now and keep up with the latest developments here until it gets to core. Ryan McCue and team have fleshed out some pretty good documentation here.


4

As far as I know wp_localize_script doesn't escape data any more than is necessary to produce valid JSON, and everything is sent as a string. The function was originally designed to allow translating the strings used in your JS into other languages (hence the "localize" part of the function name). So if the data you're passing is coming from a user input or ...


4

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' ); // ...


3

@toscho great implementation. Tested and true. Here is a slightly modified version, which also passes the $handle and $object_name so you can filter only when needed. class Filterable_Scripts extends WP_Scripts {     function localize( $handle, $object_name, $l10n )     {         $l10n = apply_filters( 'script_l10n', $l10n, $handle, $object_name );         ...


3

The function wp_localize_script() is used to send variables to a script that has already been registered and enqueued. Do you have a js file that has been registered and enqueued and has the handle of 'ajax_URL'? If not, then that explains why it isn't working. Also, ajaxurl is already a js variable that is accessible via any scripts you enqueue, so I'm ...


3

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'...


3

Your ploblem is that wp_localize_script print to the html markup a javascript object similar to: var slider = {"id":"a_unique_id_here"}; if you call it more times, e.g. using more shortcodes in same page, whati is printend in html markup is var slider = {"id":"a_unique_id_here"}; var slider = {"id":"another_unique_id_here"}; var slider = {"id":"...


3

While historically WP has been back–end centric, there had been declaration made for years now about moving towards heavy JS use. With backwards compatibility commitments in mind it is questionable that JS will achieve parity or take over PHP any time soon (in my opinion), but there had been some progress on it. The WordPress admin now ships with Backbone ...


3

To answer your statement: [...] there is no built-in Javascript API for Wordpress. Therefore developers who want to build on Ajax seem to come up all with their own solution which doesn't seem right to me. There is no "own solution" to be done. You can ease things by using ATP with ajax_template_part() by @G.M. or similar plugins and take a short cut, ...


3

You are not enqueueing your custom JavaScript file. And calling the var (templateUrl) in JS file without the handle. Follow the following: I'm enqueueing my custom JavaScripts file (script.js) under the dependency of jQuery, so it will enqueue jQuery library from core. And I'm using the same handle my-custom-js for both my script and localize_script to pass ...


3

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 you want to return from your ...


3

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() { //...


3

Why part: The Why part can be found within the WP_Scripts::localize() method: foreach ( (array) $l10n as $key => $value ) { if ( !is_scalar($value) ) continue; $l10n[$key] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8'); } where we note the (string) casting. Workarounds: The latest proposed patch suggests replacing ...


Only top voted, non community-wiki answers of a minimum length are eligible