Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php within js-file Wordpress

In a .js-file, I need to get the template-directory of a Wordpress theme, i.e. I need to get the return-value of <?php bloginfo('template_directory');?> within the js-file.

The idea is something like:

var blogTemplateDir = "<?php bloginfo('template_directory');?>";

How can this be achieved? What is the standard (Wordpress) way of doing this?

like image 654
Ben Avatar asked Jul 24 '11 16:07

Ben


1 Answers

Wordpress offers a wp_localize_script() function that allows you to pass a PHP array to a .js file when you register it with Wordpress.

It works like this

1) Register your script with Wordpress using wp_register_script(); Build an array of your parameters that you want to send to the script.

wp_enqueue_script('my-script','/path/to/script.js');

2) Build an array of your parameters that you want to send to the script.

$params = array('foo' => 'bar','setting' => 123);

3) Call wp_localize_script() and give your parameters a unique name.

wp_localize_script( 'my-script', 'MyScriptParams', $params );

4) You can access the variables in JavaScript as follows:

<script>
alert(object_name.some_string);
</script>

Note: you need to use wp_enqueue_script() when you want Wordpress to incluse the JavaScript file in the header.

Pulling it all together

<?php
$myPlugin = new MyPlugin();

//Add some JS to the admin section
add_action('admin_enqueue_scripts', array($myPlugin, 'adminJavaScript'));

class MyPlugin{

        public function adminJavaScript() {

        $settings = array(
            'foo' => 'bar',
            'setting' => 123
        );

        wp_register_script('myJavaScriptName', plugins_url('/myJavaScript.min.js', __FILE__));
        wp_localize_script('myJavaScriptName', 'settings', $settings); //pass any php settings to javascript
        wp_enqueue_script('myJavaScriptName'); //load the JavaScript file
    }
}
?>

<script>
    alert(settings.foo);
</script>
like image 77
Levi Putna Avatar answered Nov 05 '22 20:11

Levi Putna