【发布时间】:2017-11-07 04:37:46
【问题描述】:
尾部斜杠“/”只是这两者之间的区别吗?如果是这样,我可以使用trailingslashit(__DIR__)?
【问题讨论】:
尾部斜杠“/”只是这两者之间的区别吗?如果是这样,我可以使用trailingslashit(__DIR__)?
【问题讨论】:
plugin_dir_url(__FILE__)该函数为您提供文件目录的url。
plugin_dir_url(__DIR__)此功能为您提供url插件文件夹。
__FILE__这个神奇的常数会给你文件所在文件的路径。
__DIR__ 这个神奇的常量将为您提供文件所在目录的路径。
trailingslashit(__DIR__)这个函数会返回目录的路径,并在目录的路径后面加上shash。
plugin_dir_path(__FILE__)。会给你与trailingslashit(__DIR__) 相同的结果。我建议使用插件目录路径,因为它是一种 wordpress 方式。
【讨论】:
plugin_dir_path
让我们了解正在发生的事情:
wordpress的功能就这么简单:
function plugin_dir_path( $file ) {
return trailingslashit( dirname( $file ) );
}
所以,
include plugin_dir_path(__FILE__) . 'xx.php';
等于
include trailingslashit( dirname( __FILE__ ) ) . 'xx.php';
在 PHP 5.3 中,__DIR__ 被引入以替代 dirname( __FILE__ )。
如果你不需要支持 PHP
include trailingslashit( __DIR__ ) . 'xx.php';
(另见:Is there any difference between __DIR__ and dirname(__FILE__) in PHP?)
由于__DIR__ 不会返回带有斜杠的内容,因此无需执行trailingslashit 的操作。所以我们可以进一步简化为:
include __DIR__ . '/xx.php';
因此,总而言之,以下几行都做了完全相同的事情(在 PHP >= 5.3 上):
include plugin_dir_path(__FILE__) . 'xx.php';
include trailingslashit( dirname( __FILE__ ) ) . 'xx.php';
include trailingslashit( __DIR__ ) . 'xx.php';
include __DIR__ . '/xx.php';
哪个最好?我更喜欢最后一个。您不必输入那么多,它的噪音更小,而且您不必担心 plugin_dir_path 函数内部有什么魔力。这就是您通常在 PHP 中包含文件的方式。一些牧师可能会说你应该用 Wordpress 的方式来做。做一个叛逆者!
【讨论】:
__DIR__ 的值,并在其他地方重用该常量,因此您可以确保您的包含和要求始终与插件/主题根文件夹。这很有用,因为__DIR__ 将指向每个文件夹中的不同文件夹。如果您出于某种原因移动文件,可能会导致问题。我只是首先创建一个 const define( 'MYPLUGINNAME_BASEDIR', __DIR__ );,然后在任何地方重用它。我的 IDE (PHPStorm) 也可以正确解决这个问题,使 include / require 检查再次有用。
/home/www/your_site/wp-content/plugins/your-plugin/includes/
这可用于加载 PHP 文件。
更多信息:https://developer.wordpress.org/reference/functions/plugin_dir_path/
http://example.com/wp-content/plugins
更多信息:https://codex.wordpress.org/Function_Reference/plugins_url
http://example.com/wp-content/plugins/
后两者对于加载图片、样式表、JS 很有用。
更多信息:https://codex.wordpress.org/Function_Reference/plugin_dir_url
【讨论】: