Skip to content

PHP WordPress Find Root Directory Regardless Of Script Location

PHP WordPress Find Root Directory Regardless Of Script Location

Sometimes you might be developing a theme, or a plugin, or an external script that connects to your WordPress installation, and you need to know where your root path, also known as ABSPATH, is. And you certainly don’t want to be hardcoding that directory path (eww.. thats disgusting) .

The solution to this problem is to use recursion to traverse the directories upwards. Very simple, elegant and clean. We all know WordPress comes with core files such as wp-load.php. So if our current directory doesn’t have these core files, it means we are not at the right directory yet, and have to go upwards again – to the parent folder

Here’s the code

/*
* Your root directory is where your wp-files.php are, e.g wp-load.php
* So basically, from whereever your script is running, just traverse upwards and you will eventually
* find your root directory (aka ABSPATH)
*/
function find_root_dir($current_dir)
{
    if( file_exists($current_dir . "wp-load.php") ) {
        return $current_dir;
    } else {
        return find_root_dir($current_dir . "../");
    }
}

 

Enjoyed the content ? Share it with your friends !
Published inDevelopmentProgramming

Be First to Comment

Leave a Reply

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