Print This Post

Inject PHP variables into Javascript

WordPress offers a simple way to add javascript code to your site.

Example:

wp_deregister_script('scriptname'); // Optional

wp_register_script(‘scriptnamey’, get_bloginfo(‘template_directory’) . ‘/js/scriptname.js’);

wp_enqueue_script(‘scriptname’);

This code adds the script scriptname.js from the themes js directory to your site.

If you want to inject a PHP variable into javascript, here is an example:

$script_params = array(

‘magic’ => 42,

‘something’ => ‘And now to something completely different’

);

wp_enqueue_script(‘myinjectexample’, get_bloginfo(‘template_directory’) . ‘/js/javascript.js’);

wp_localize_script(‘myinjectexample’, ‘scriptParams’, $script_params);

 

and in your script “javascript.js” you cann access this variables from PHP like

console.log(scriptParams.magic);

console.log(scriptParams.something);

 

Easy and fast…

Kommentare

Keine Kommentare bisher

Hinterlassen Sie einen Kommentar