问题描述
我的插件使用以下代码来引用一个文件,但如果用户重命名默认的插件文件夹,我已经阅读 WP_PLUGIN_DIR
将无法正常工作。我也想用/location-specific-menu-items/
替代当前的插件文件夹。
$gi = geoip_open(WP_PLUGIN_DIR ."/location-specific-menu-items/GeoIP.dat", GEOIP_STANDARD);
无论 WP 插件目录和特定插件文件夹的名称如何,我如何可以重写此操作?
编辑:
这是我最后的工作解决方案,遵循每个人的意见。非常感谢!
$GeoIPv4_file = plugin_dir_path( __FILE__ ) . 'data/GeoIPv4.dat';
$GeoIPv6_file = plugin_dir_path( __FILE__ ) . 'data/GeoIPv6.dat';
if (!filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === FALSE) {
if ( is_readable ( $GeoIPv4_file ) ) {
$gi = geoip_open( $GeoIPv4_file, GEOIP_STANDARD );
$user_country = geoip_country_code_by_addr($gi, $ip_address);
geoip_close($gi);
}
} elseif (!filter_var($ip_address, FILTER_VALIDATE_IP,FILTER_FLAG_IPV6) === FALSE) {
if ( is_readable ( $GeoIPv6_file ) ) {
$gi = geoip_open( $GeoIPv6_file, GEOIP_STANDARD );
$user_country = geoip_country_code_by_addr($gi, $ip_address);
geoip_close($gi);
}
} else {
$user_country = "Can't locate IP: " . $ip_address;
}
最佳解决方案
如果插件结构是:
plugins/
some-plugin/
some-plugin.php
data/
GeoIP.dat
那么对于 PHP 5.3.0+,你可以尝试魔术常数__DIR__
__DIR__
The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent todirname(__FILE__)
. This directory name does not have a trailing slash unless it is the root directory.
在 some-plugin.php
文件中:
// Full path of the GeoIP.dat file
$file = __DIR__ . '/data/GeoIP.dat';
// Open datafile
if( is_readable ( $file ) )
$gi = geoip_open( $file, GEOIP_STANDARD );
对于更广泛的 PHP 支持,您可以使用 dirname( __FILE__ )
,其中在 PHP 4.0.2 中添加了__FILE__
。
次佳解决方案
您可以使用:
plugin_dir_path(__FILE__);
哪个只是一个包装功能呢?
trailingslashit(dirname(__FILE__));
参考文献
注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。