Can we somehow use wp_localize_script() to create global js variables without a specific script handle which can be accessed from all the js files, even if the js scripts are not enqueued properly by using wp_enqueue_script ?
This is the code I am using which creates varibale for ‘ajaxscript’ handle, so I cant access the object ‘ajaxobject’ in a js file which is being included in the header.php directly by <script src="xxx" .... />
wp_register_script( 'ajaxscript', get_bloginfo( 'template_url' ) . '/js/ajaxscript.js', array(), $version );
wp_enqueue_script( 'ajaxscript' );
wp_localize_script( 'ajaxscript', 'ajaxobject',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'ajaxnonce' => wp_create_nonce( 'itr_ajax_nonce' )
)
);
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:
Also as suggested by @Weston Ruter, you should json encode the variables:
You can export any data you want in the
wp_head
hook, as the answers above show. However, you should usejson_encode
to prepare the PHP data for exporting to JS instead of trying to embed raw values into JS literals:Using
json_encode
makes it easier on yourself, and it prevents accidental syntax errors if your string includes any quote marks. Even more importantly, usingjson_encode
thwarts XSS attacks.I ended up doing this. It works now !! Thanks @dot1
While this isn’t my finest work, this is another straight-forward way to accomplish putting data in the response:
Add some JS data to the window context:
This will work for either the header scripts or footer scripts and won’t repeat itself.