skip to Main Content

I can get the dir/url of a plugin’s file by using:

            $plugin_dir_path = plugin_dir_path(__FILE__);
            $plugin_dir_url = plugin_dir_url(__FILE__);

However, if the file calling the above codes are in a subdir such as ./includes, the the subdir will also be returned, like this:

/xxx/wp-content/plugins/file-converter/includes/

How to get the root dir of the plugin without the subdir? i.e. /xxx/wp-content/plugins/file-converter/

2

Answers


  1. in my plugin, a create these hooks in the main file :

    add_filter("MY_PLUGIN/root_extension", function ($r) {
        return __DIR__;
    });
    add_filter("MY_PLUGIN/url_extension", function ($r) {
        return plugins_url("", __FILE__);
    });
    

    and then I can use them in all my files with this code :

    $url_extension = apply_filters("MY_PLUGIN/url_extension", NULL);
    $root_extension = apply_filters("MY_PLUGIN/root_extension", NULL);
    
    Login or Signup to reply.
  2. There are many ways to handle that.
    I noticed that WordPress plugins use constants to set those in the main plugin file, like:

    defined( 'FILE_CONVERTER_DIR_PATH' ) || define( 'FILE_CONVERTER_DIR_PATH', plugin_dir_path(__FILE__) );
    defined( 'FILE_CONVERTER_DIR_URL' ) || define( 'FILE_CONVERTER_DIR_URL', plugin_dir_url(__FILE__) );
    

    Then you can use directly FILE_CONVERTER_DIR_PATH or FILE_CONVERTER_DIR_URL constants from any included plugin PHP file, to retrieve the right directory path or directory URL.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search