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?
Wrap the .js in a .php file and just include it in your context.
The file extension for a javascript file is meaningless. You can use PHP to output your javascript file just like you do HTML pages. Include the JS file as:
And then you can use the line from your question in your javascript file:
As Erik earlier posted, the file extension for the JavaScript-file is meaningless, as it in the end all comes down to the content. Upon encountering this situation during development, I found that I needed to add the following to the top of the so called JavaScript-file:
This ensures that you get the definitions into your JavaScript-file, and you can use the example above with themes too (just make sure you change the
/plugins
into/themes
instead).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.
2) Build an array of your parameters that you want to send to the script.
3) Call wp_localize_script() and give your parameters a unique name.
4) You can access the variables in JavaScript as follows:
Note: you need to use wp_enqueue_script() when you want Wordpress to incluse the JavaScript file in the header.
Pulling it all together