Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

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?

share|improve this question
1  
Couldn't you just use ABSPATH? Also, remember to phrase your question in Q&A-style format –  bungeshea Dec 18 '12 at 8:12
    
Since I have to determine the base path to be able to load the wordpress core it is not loaded yet. ABSPATH is not defined then. I will look into the link you gave me and edit according to it, thanks for this =) –  xaedes Dec 18 '12 at 8:18
add comment

1 Answer

up vote 2 down vote accepted

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;
}
share|improve this answer
    
wp_config.php can reside in the directoy above wordpress root. Anyway usually if you need to find where wordpress is installed then you are doing something totally wrong. –  Mark Kaplun Dec 18 '12 at 9:49
    
Good point. Which file would be better to check for? –  xaedes Dec 18 '12 at 10:35
    
guess you need to verify by first checking for wp-config.php and then checking if index.php is in that dirctory or the one below it. –  Mark Kaplun Dec 18 '12 at 10:52
2  
Probably, yours is the intelligent version of this: wp-load, I'll find you. I like Frank's method. –  brasofilo Dec 18 '12 at 11:00
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.