問題描述

我的外掛使用以下程式碼來引用一個檔案,但如果使用者重新命名預設的外掛資料夾,我已經閱讀 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 to dirname(__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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。