Wordpress - Is it possible to use wp_localize_script to create global JS variables without a specific script handle?
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( "itr_ajax_nonce" ); ?>';
</script><?php
}
add_action ( 'wp_head', 'my_js_variables' )
Also as suggested by @Weston Ruter, you should json encode the variables:
add_action ( 'wp_head', 'my_js_variables' );
function my_js_variables(){ ?>
<script type="text/javascript">
var ajaxurl = <?php echo json_encode( admin_url( "admin-ajax.php" ) ); ?>;
var ajaxnonce = <?php echo json_encode( wp_create_nonce( "itr_ajax_nonce" ) ); ?>;
var myarray = <?php echo json_encode( array(
'foo' => 'bar',
'available' => TRUE,
'ship' => array( 1, 2, 3, ),
) ); ?>
</script><?php
}
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" ) ) ?>;
var ajaxnonce = <?php echo json_encode( wp_create_nonce( "itr_ajax_nonce" ) ) ?>;
var myarray = <?php echo json_encode( array(
'food' => 'bard',
'bard' => false,
'quux' => array( 1, 2, 3, ),
) ) ?>;
</script>
<?php
}
add_action ( 'wp_head', 'my_js_variables' )
Using json_encode
makes it easier on yourself, and it prevents accidental syntax errors if your string includes any quote marks. Even more importantly, using json_encode
thwarts XSS attacks.