Last active
August 29, 2015 14:00
-
-
Save nickpelton/11219922 to your computer and use it in GitHub Desktop.
WP: Localize Script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// enque script | |
wp_enqueue_script( "myScript", get_template_directory_uri()."/js/myscript.js", array('jquery'), '1.0',true); | |
// Setup our data | |
$myDataArray = array( | |
'data' => array( // Add some data | |
'person' => array( | |
'name'=>'Nick', | |
'job' => 'Developer' | |
) | |
) | |
); | |
// Pass data to myscript.js on page load | |
wp_localize_script( "myScript", "myLocalizedData", $myDataArray ); | |
// wp_localize_script( $handle, $objectName, $arrayOfValues ); | |
// $handle - The enqueued script to place the data immedietly before | |
// $objectName - Name of the JS object that will hold the data | |
// $arrayOfValues - Data to pass to JS |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ = jQuery.noConflict(); | |
jQuery(document).ready(function(){ | |
/** | |
* Accessing data passed to JS from WP on page load | |
*/ | |
// Place Data in DOM | |
$('#displayData').append("Name: "+myLocalizedData.data.person.name+"<br>"); | |
$('#displayData').append("Job: "+myLocalizedData.data.person.job+"<br>"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment