strange behavior of wp_enqueue_script on a local xampp install

只谈情不闲聊 提交于 2019-12-12 01:43:25

问题


I want to call a js file with wp_enqueue_script.

I use get_template_directory(), like so:

$myfile = wp_normalize_path(get_template_directory().'/js/script.js');
$myversion = filemtime($myfile);
wp_enqueue_script('myscript', $myfile , array( 'jquery' ), $myversion, true );

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.

(Note that the above - at least the filemtime part- would fail if I used get_template_directory_uri.)

On my local xampp install (Windows machine), this doesn't work.

If I do echo $myfile, it returns the correct local path:

D:/path/to/folder/wp-content/themes/mytwentysixteen/js/script.js

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

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 doesn't seem to help.


回答1:


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

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.



来源:https://stackoverflow.com/questions/41265585/strange-behavior-of-wp-enqueue-script-on-a-local-xampp-install

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!