wp_enqueue_script在本地xampp安装上的奇怪行为 [英] strange behavior of wp_enqueue_script on a local xampp install
问题描述
我想用wp_enqueue_script
调用js文件.
我使用get_template_directory()
,就像这样:
$myfile = wp_normalize_path(get_template_directory().'/js/script.js');
$myversion = filemtime($myfile);
wp_enqueue_script('myscript', $myfile , array( 'jquery' ), $myversion, true );
这在服务器上有效:如果我回显$myfile
,它将返回真实路径,例如/home/public_html/folder/wp-content/themes/mytwentysixteen/js/script.js
,而在网页上,它将正确返回文件的绝对路径.
this works on the server: If I echo $myfile
, it returns a real path, like /home/public_html/folder/wp-content/themes/mytwentysixteen/js/script.js
, while on the web page it returns the absolute path to the file correctly.
(请注意,如果使用get_template_directory_uri
,以上内容-至少filemtime
部分将失败.)
(Note that the above - at least the filemtime
part- would fail if I used get_template_directory_uri
.)
在我的本地xampp安装(Windows计算机)上,这不起作用.
On my local xampp install (Windows machine), this doesn't work.
如果执行echo $myfile
,它将返回正确的本地路径:
If I do echo $myfile
, it returns the correct local path:
D:/path/to/folder/wp-content/themes/mytwentysixteen/js/script.js
但是,在wp_enqueue_script
之后,在网页上它返回的内容如下:
However, following wp_enqueue_script
, on the web page it returns something like this:
http://localhost/folderD:pathtofolder/wp-content/themes/mytwentysixteen/js/script.js
,页面无法检索脚本. 这似乎是本地主机上的本地URL与本地Windows路径之间的奇怪结合.
and the page fails to retrieve the script. This seems an odd marriage between the home url on localhost and the local windows path.
wp_normalize_path
似乎没有帮助.
推荐答案
显然,解决方案是get_template_directory()
不应用于排队脚本,而应用于filemtime
之类的php函数.
Apparently the solution is that get_template_directory()
should not be used to enqueue scripts, but it should be used for php functions like filemtime
.
因此,解决方案是将两者分开,就像这样:
Therefore, the solution is to separate the two, like so:
$myfile = get_template_directory_uri().'/js/script.js';
$myversion = filemtime(get_template_directory().'/js/script.js');
wp_enqueue_script('myscript', $myfile , array( 'jquery' ), $myversion, true );
在这里,我使用get_template_directory_uri()
来检索脚本,并使用get_template_directory()
来获取文件的时间戳,并且都可以在xampp上正常工作.
Here I use get_template_directory_uri()
to retrieve the script, and get_template_directory()
to get the timestamp of the file and both work on xampp without a problem.
这篇关于wp_enqueue_script在本地xampp安装上的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!