Have you ever needed to locate the root folder for a WordPress installation? If you’re checking from a page that is loaded up as part of WP, it’s easy; just use the ABSPATH constant, which is set up at the top of your wp-load.php file.

wpcodeHowever, if you need the root folder from within a page that is outside of WP, it’s a little more tricky. You don’t have access to the ABSPATH constant, and you don’t have built in access to the database to check for ‘wp_dir’ in the options table. [Of course, you could query the db if you have access details: something like “select option_value from wp_options where option_name ='wp_dir';” would do it.]

If the page is in a folder that is below the WP root folder though, there’s a nicer way. I wrote a little recursive function that checks a folder for the existence of a named file and, if it’s not there, moves to the parent folder and checks again. If it’s found, it returns the path to the file. So, if the file is below the root folder, this function will eventually find the root WP folder if you search for something like ‘wp-load.php’ or something else that generally lives in that folder.

Here’s the function with some code to demo how it’s used:

function find_file($filename, $path){
	$filepath = $path.'/'.$filename;
	if (!file_exists($filepath)){
		$filepath = find_file($filename, dirname($path));
	}
	return $filepath;
}
 
$path_to_wpload = find_file('wp-load.php', __DIR__);

Hopefully that’s useful to someone. If you have an improvement to the function, or another (better) way to do the same thing, please add a comment.