How to determine wordpress base path when wordpress core is not loaded

I have a command line script for maintaining a wordpress plugin and have to determine the wordpress base path to be able to load the wordpress core.

I could just assume the script is several levels under the base path. But if I want to reuse the code and I have another similar script that needs to determine the wordpress base path I would have to adjust the level depth. This is error prone.

Read More

edit: ABSPATH can’t be used since it is not defined in the command line script. In fact its value is necessary to be able to load the wordpress core and which will define it.

So how do I determine the wordpress base path when the wordpress environment is not loaded yet?

Similar question: What is the best way to get directory path for wp-config.php?

Related posts

Leave a Reply

1 comment

  1. I came up with this solution.

    This function checks in each directory level starting from the directory of the current file for the file wp-config.php. If it is found the directory is to be assumed the wordpress base path.
    The check can of course be changed to other wordpress core files.

    function find_wordpress_base_path() {
        $dir = dirname(__FILE__);
        do {
            //it is possible to check for other files here
            if( file_exists($dir."/wp-config.php") ) {
                return $dir;
            }
        } while( $dir = realpath("$dir/..") );
        return null;
    }