Is it possible to use wp_localize_script to create global JS variables without a specific script handle?

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="" .... />

wp_register_script( 'ajaxscript', get_bloginfo( 'template_url' ) . '/js/ajaxscript.js', array(), $version );
wp_enqueue_script( 'ajaxscript' );
wp_localize_script( 'ajaxscript', 'ajaxobject',
        '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

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" ); ?>";
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, ),
       ) ); ?>

Leave a Comment