Skip to content

Instantly share code, notes, and snippets.

@glueckpress
Last active December 14, 2015 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glueckpress/4722102 to your computer and use it in GitHub Desktop.
Save glueckpress/4722102 to your computer and use it in GitHub Desktop.
[WordPress] Basic routine to pass an array of values from PHP to JavaScript.
<?php
/* Create an array of data to pass */
$obj = array(
'foo' => $foo,
'bar' => $bar,
'multifoo' => array( 'foo1', 'foo2' )
);
/* Enqueue javascript (assuming jQuery has been enqueued already) */
wp_enqueue_script( 'script-handler', 'plugin-script.js', 'jquery', false, true );
/* Pass array as javascript object */
wp_localize_script( 'script-handler', 'obj', $obj );
;(function($){
// Create object from PHP array values
$.Obj = {
foo : obj.foo,
bar : obj.bar,
multifoo : obj.multifoo // obj.multifoo[0], obj.multifoo[1] usw.
}
// Check values in console
console.log(
'foo: ' + $.Obj.foo +"\n"+
'bar: ' + $.Obj.bar +"\n"+
'multifoo [0]: ' + $.Obj.multifoo[0] +', '+
'multifoo [1]: ' + $.Obj.multifoo[1] +', '+
'multifoo [2]: ' + $.Obj.multifoo[2]
);
}(jQuery))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment