now using wp_localize instead of wp_add_inline
This commit is contained in:
@@ -35,24 +35,41 @@ function add_files_to_front($files_arr) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
|
||||
@param expect an array of key => value
|
||||
with the key being name of the variable, like this :
|
||||
'my_var' => 'value',
|
||||
simpler way to do it is to use compact when calling the function :
|
||||
add_var_to_front(compact("var1", "var2", "var3"));
|
||||
pass variables to front as global variables, accessible in js as an object
|
||||
@param two params :
|
||||
1. an array of key => value
|
||||
with the key being name of the variable, like this :
|
||||
'my_var' => 'value',
|
||||
simpler way to do it is to use compact when calling the function :
|
||||
add_var_to_front(compact("var1", "var2", "var3"));
|
||||
2. name of first embended script (if we want to have the variables
|
||||
availables to all js : it will be available to the script and all following)
|
||||
- default value is "init", assuming the first script is called "init.js"
|
||||
old version :
|
||||
- was using wp_add_inline_script() which is rather for scripts than variables
|
||||
- it had to write explicitly the variable declaration as "const myvar = 'value'"
|
||||
*/
|
||||
function add_var_to_front($var_array) {
|
||||
extract($var_array);
|
||||
function add_var_to_front($vars, $handle = "init") {
|
||||
$handle = pathinfo($handle, PATHINFO_FILENAME);
|
||||
$object_name = "php_data";
|
||||
|
||||
foreach ($var_array as $key => $var)
|
||||
{
|
||||
$js_var = 'const ' . $key . ' = ';
|
||||
$js_var .= json_encode($var);
|
||||
$js_var .= ';';
|
||||
wp_add_inline_script('myscript', $js_var, 'before');
|
||||
}
|
||||
wp_localize_script($handle, $object_name, $vars);
|
||||
}
|
||||
// function add_var_to_front($vars, $handle = "init") {
|
||||
// extract($vars);
|
||||
// $handle = pathinfo($handle, PATHINFO_FILENAME);
|
||||
//
|
||||
// foreach ($vars as $key => $var)
|
||||
// {
|
||||
// $js_var = 'const ' . $key . ' = ';
|
||||
// $js_var .= json_encode($var);
|
||||
// $js_var .= ';';
|
||||
// wp_add_inline_script($handle, $js_var, 'before');
|
||||
// }
|
||||
// }
|
||||
|
||||
?>
|
||||
|
||||
Reference in New Issue
Block a user