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

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.

<?php
    function find_wp_config_path() {
        $dir = dirname(__FILE__);
        do {
            if( file_exists($dir."/wp-config.php") ) {
                return $dir;
            }
        } while( $dir = realpath("$dir/..") );
        return null;
    }
?>

To actually include the file you can use this:

if ( ! function_exists('add_action') ) {
    include_once( find_wp_config_path()  . '/wp-load.php' );
}

This can also be found here:
How to determine wordpress base path when wordpress core is not loaded

Leave a Comment