strange behavior of wp_enqueue_script on a local x

2019-09-19 08:13发布

问题:

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.