WordPress – get_template_directory_uri() in Jquery and CSS


I am trying to use get_template_directory_uri() to load images to a jquery.backstretch.js file and to my styles.css as well. So far, I added my images directly in the theme folder in a folder named "img" and I have used this for my HTML:

 <img src="<?php echo get_template_directory_uri(); ?>/img/logoyellow.png" class="hidden-xs" alt="logo" />

That worked fine!

But I did the following in a jquery file (jquery.backtretch.js):

  $(document).ready(function () {
       $("#home-section").backstretch("<?php echo get_template_directory_uri(); ?>/img/background-image2.jpg");

But no cigar 🙁 I also wold like to know how to load it in my CSS. Something like this:

  #milestones-section {
      background: url('<?php echo get_template_directory_uri(); ?>/img/hbg.jpg') center center;

Thanks in advance!

Best Solution

JS files aren't parsed by PHP, so you won't get access to functions like get_template_directory_uri().

The Quick and Dirty Way

You can make that available to Javascript by putting something like this in the <head> of each page:

    theme_directory = "<?php echo get_template_directory_uri() ?>";

The Right Way

You should probably load js in the correct Wordpress manner, using wp_register_script() and/or wp_enqueue_script(). If you do that, you can use the Wordpress function wp_localize_script() and make whatever information you like available to that script.

More information: http://codex.wordpress.org/Function_Reference/wp_localize_script


You CSS files should already be in the theme directory, so you can use relative paths for that.

Related Question