Wordpress wp_localize_script

Leave a Comment
Wordpress offers wp_localize_script() function to assign some value from php to Javascript. This wp_localize_script() function makes any php data that's directly available in JavaScript.

<?php wp_localize_script( $handle, $name, $data );  ?> 

Where $handle – refers to script file
           $name – refers to name of the JavaScript object.
           $data – where we can specify list parameters for that JavaScript object ($name) going to have.

For example I want following php data you want in ajax.js file. So we need to do following things.
// Register the script
wp_register_script( 'ajax', 'path/to/ajax.js' );
wp_localize_script( 'ajax', 'php_data', array( 'name' => 'muni' ) );
// Enqueued script with localized data.
wp_enqueue_script( 'ajax' );

While your page is excuted it will generate following scripts in your page.
<script type='text/javascript'>
/* <![CDATA[ */
var php_data = {"name":"muni"};
/* ]]> */
<script type='text/javascript' src='http://localhost/developersguide/wp-content/themes/developersguide/library/js/ajax.js'></script>

So we can easily access that php data in JavaScript like below.
alert( php_data.name);

To know more about please refer following Wordpress Forntend Login Tutorial.

 Light Weight WordPress Frontend Ajax Login and Registration


Post a Comment