問題描述
我的插件使用以下代碼來引用一個文件,但如果用户重命名默認的插件文件夾,我已經閲讀 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。