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!
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:The Right Way
You should probably load js in the correct WordPress manner, using
wp_register_script()
and/orwp_enqueue_script()
. If you do that, you can use the WordPress functionwp_localize_script()
and make whatever information you like available to that script.More information: http://codex.wordpress.org/Function_Reference/wp_localize_script
CSS
You CSS files should already be in the theme directory, so you can use relative paths for that.
Chris Herbert works well
but if anybody need it to write this to innerHTML, for Example on a button:
1.) insert into example.php file:
2.) in script.js file:
Maybe it helps