简体   繁体   English

WordPress 和 jQuery - 导入<?php bloginfo('url'); ?>到脚本文件

[英]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'); ?>我正在使用 Wordpress,我想使用<?php bloginfo('url'); ?> <?php bloginfo('url'); ?> in a jQuery script file as a variable. <?php bloginfo('url'); ?>在 jQuery 脚本文件中作为变量。 Is that possible?那可能吗? And how?如何?

In my script.js file I a function that uses:在我的 script.js 文件中,我使用了一个函数:

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

and the "http://www.mysite.com" part will change (I'm building a theme).并且“http://www.mysite.com”部分将会改变(我正在构建一个主题)。

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:您所要求的并不容易实现,而是在您的<head>元素中设置一个 JavaScript 变量:

<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:然后你可以在任何 JS 文件中使用site_url变量:

alert(site_url);

August 2020 update 2020 年 8 月更新

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.您应该查看 WordPress 的wp_localize_script函数,这允许您指定要提供给排队脚本的其他数据。

Here's a good example by mikeschinkel on Github .这是mikeschinkel 在 Github 上的一个很好的例子。

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

But why can't you use relative URLs?但是为什么不能使用相对 URL 呢?

$("#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.我建议使用admin_url('admin-ajax.php')而不是使用http://my-site.com/ajax ,它是在 WP 中处理 ajax 调用的标准入口点。 Also, there is wp_localize_script function that will help you declaring JS variable.此外,还有wp_localize_script函数可以帮助您声明 JS 变量。

I imagine you'll have to run you Javascript file through PHP and use instead of "http://www.mysite.com/ajax/".我想你必须通过 PHP 运行你的 Javascript 文件并使用而不是“http://www.mysite.com/ajax/”。

You can also try to use window.location which is a Javascript property.您也可以尝试使用 window.location 这是一个 Javascript 属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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