My plugin uses the following code to reference a file, but I’ve read WP_PLUGIN_DIR won’t work if a user renames the default plugin folder. I would also like to replace /location-specific-menu-items/with a reference to the current plugin folder.

$gi = geoip_open(WP_PLUGIN_DIR ."/location-specific-menu-items/GeoIP.dat", GEOIP_STANDARD);

How could I rewrite this to make it work regardless of the names of the WP plugin directory and the specific plugin folder?

EDIT:

Here is my final working solution following everyone’s input. Many thanks!

$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;              
}   

3 s
3

If the plugin structure is:

plugins/
   some-plugin/
       some-plugin.php
       data/
           GeoIP.dat

then for PHP 5.3.0+, you could try the magic constant __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.

within the some-plugin.php file:

// Full path of the GeoIP.dat file
$file =  __DIR__ . '/data/GeoIP.dat';

// Open datafile
if( is_readable ( $file ) ) 
    $gi = geoip_open( $file, GEOIP_STANDARD );

For wider PHP support you could use dirname( __FILE__ ), where __FILE__ was added in PHP 4.0.2.

Leave a Reply

Your email address will not be published. Required fields are marked *