Global js variable in WordPress

If you are a WordPress Theme or Plugin developer, then you might already know this, in case you don’t, It’ll come real handy for you.

We often require some values or arrays to be available locally to theme or plugin js, If it is required for a specific JS, you can easily make it available to JS by using WordPress function:

wp_localize_script();

But in case you need the same variable to be available to multiple JS, you can do it so by hooking the JS variable at wp_head

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
}

Above code echoes the variables in <head></head> section of your page, and hence you can use all the variables in your custom Javascript , wherever you want.

You can conditionally echo the code on only few templates or specific pages. Here is an example:

add_action ( 'wp_head', 'my_js_variables' );
function my_js_variables(){ 

 //for specific page templates
 $current_template =  get_page_template();

// return if there is no page template, or if the page template is other than template-x1.php or template-x2.php
 if( !isset($current_template) || ( $current_template != 'template-x1.php' && $current_template != 'template-x2.php' ) ){  return; } ?>
  <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
}

Hope it helps someone šŸ™‚

Cheers, Happy Coding..!!

1 thought on “Global js variable in WordPress”

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.