'I need to define <?php bloginfo('template_directory'); ?> within my jQuery script. How?

I know that when using Wordpress, in a php file you can say

<img src="<?php bloginfo('template_directory'); ?>/images/image.png"/>

and it knows that you want the current template directory, so that you can make a plugin universal.

I want to add some html dynamically using jQuery that includes something like <?php bloginfo('template_directory'); ?> to define my path.

So my question is, how do get and then define my template path in jQuery?



Solution 1:[1]

Create a variable in javascript:

<script type="text/javascript">
   var templateDirectory = '<?php bloginfo('template_directory'); ?>';
</script>

From there you can do whatever you want, like so:

$('#my-image').attr('src', templateDirectory + '/images/image.png');

Solution 2:[2]

PHP is server-side, so once everything executes on the server and the page loads, you can't change the PHP with client-side code. The code provided by Nathan is right, but the quotes aren't quite right. You'd want something like this:

<script type="text/javascript">
   var templateDirectory = "<?php bloginfo('template_directory'); ?>";
</script>

Check to see if that function returns a value or actually echoes it out. If it returns the value, you'll want it echoed instead (since you want the actual output of the bloginfo() function echoed into the javascript variable). The easiest way to do that without changing the function itself is to just echo it:

<script type="text/javascript">
   var templateDirectory = "<?php echo bloginfo('template_directory'); ?>";
</script>

Hope that helps!

Solution 3:[3]

You can use a combination of get_theme_root_uri()& get_template

$qrImgLink = get_theme_root_uri()."/".get_template()."/qr/".$RandomToken.".png";

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nathan Anderson
Solution 2 Aaron
Solution 3 Wael Wafik