get_template_directory_uri() in Jquery and CSS

你。 提交于 2019-12-12 04:54:39

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/28333384/get-template-directory-uri-in-jquery-and-css

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!