【问题标题】:strange behavior of wp_enqueue_script on a local xampp installwp_enqueue_script 在本地 xampp 安装上的奇怪行为
【发布时间】:2017-05-07 01:01:31
【问题描述】:

我想用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,而在网页上它会正确返回文件的绝对路径。

(请注意,如果我使用 get_template_directory_uri,上述内容 - 至少 filemtime 部分会失败。)

在我的本地 xampp 安装(Windows 机器)上,这不起作用。

如果我做echo $myfile,它会返回正确的本地路径:

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

但是,在wp_enqueue_script 之后,它在网页上返回如下内容:

http://localhost/folderD:pathtofolder/wp-content/themes/mytwentysixteen/js/script.js

并且页面无法检索脚本。 这似乎是 localhost 上的 home url 和本地 windows 路径之间的奇怪结合。

wp_normalize_path 似乎没有帮助。

【问题讨论】:

    标签: php wordpress path xampp


    【解决方案1】:

    显然解决方案是 get_template_directory() 不应该用于入队脚本,但它应该用于像 filemtime 这样的 php 函数。

    因此,解决方案是将两者分开,如下所示:

    $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 上正常工作。

    【讨论】:

      猜你喜欢
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 2016-09-17
      • 2015-06-02
      • 2011-11-22
      • 1970-01-01
      • 2014-10-27
      • 2023-03-10
      相关资源
      最近更新 更多