简体   繁体   中英

Wordpress & jQuery - import <?php bloginfo('url'); ?> to script file

I'm using Wordpress and I would like to use the value of <?php bloginfo('url'); ?> <?php bloginfo('url'); ?> in a jQuery script file as a variable. Is that possible? And how?

In my script.js file I a function that uses:

$("#board").load("http://www.mysite.com/ajax/",{slug:post_slug});

and the "http://www.mysite.com" part will change (I'm building a theme).

Many thanks for your time and help.

What you're asking for is not easily achieved, instead set a JavaScript variable in your <head> element:

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

Then you can use the site_url variable in any of your JS files:

alert(site_url);

August 2020 update

You should check out WordPress' wp_localize_script function instead, this allows you to specify additional data to be made available to a queued script.

Here's a good example by mikeschinkel on Github .

var bloginfo_url = "<?php bloginfo('url'); ?>";
$("#board").load(bloginfo_url + "/ajax/", {slug:post_slug});

But why can't you use relative URLs?

$("#board").load("/ajax/", {slug:post_slug});

Instead of using http://my-site.com/ajax , I would recommend using admin_url('admin-ajax.php') which is a standard entry point for handling ajax calls in WP. Also, there is wp_localize_script function that will help you declaring JS variable.

I imagine you'll have to run you Javascript file through PHP and use instead of "http://www.mysite.com/ajax/".

You can also try to use window.location which is a Javascript property.

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