简体   繁体   中英

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'); ?> <?php bloginfo('template_directory'); ?> to define my path.

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

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');

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!

You can use a combination of get_theme_root_uri()& get_template

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM