Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 725
LOTUSMS Avatar asked Dec 05 '22 04:12

LOTUSMS


2 Answers

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:

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

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

CSS

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

like image 88
Chris Herbert Avatar answered Dec 24 '22 21:12

Chris Herbert


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:

<?php 
function loadDirectory() { ?>
<script type="text/javascript">
    var theme_directory = "<?php echo get_template_directory_uri() ?>";
</script> 
<?php } 
add_action('wp_head', 'loadDirectory'); ?>

2.) in script.js file:

document.getElementById('exampleButton').innerHTML = '<img src="' + theme_directory + '/svg/icons/cursor.svg" width="32" height="32" title="">Example';

Maybe it helps

like image 38
Koppi Avatar answered Dec 24 '22 20:12

Koppi