How can I retrieve the path to the root directory in WordPress CMS?
For retrieving the path you can use a function <?php $path = get_home_path(); ?>
. I do not want to just repeat what had been already said here, but I want to add one more thing:
If you are using windows server, which is rare case for WordPress installation, but still happens sometimes, you might face a problem with the path output. It might miss a "\" somewhere and you will get an error if you will be using such a path. So when outputting make sure to sanitize the path:
<?php
$path = get_home_path();
$path = wp_normalize_path ($path);
// now $path is ready to be used :)
?>
If you have WordPress bootstrap loaded you can use get_home_path() function to get path to the WordPress root directory.
Please try this for get the url of root file.
First Way:
$path = get_home_path();
print "Path: ".$path;
// Return "Path: /var/www/htdocs/" or
// "Path: /var/www/htdocs/wordpress/" if it is subfolder
Second Way:
And you can also use
"ABSPATH"
this constant is define in wordpress config file.
I like @Omry Yadan's solution but I think it can be improved upon to use a loop in case you want to continue traversing up the directory tree until you find where wp-config.php
actually lives. Of course, if you don't find it and end up in the server's root then all is lost and we return a sane value (false
).
function wp_get_web_root() {
$base = dirname(__FILE__);
$path = false;
while(!$path && '/' != $base) {
if(@file_exists(dirname($base)).'/wp-config.php') {
$path = dirname($base);
} else {
$base = dirname($base);
}
}
return $path;
}
I think this would do the trick:
function get_wp_installation()
{
$full_path = getcwd();
$ar = explode("wp-", $full_path);
return $ar[0];
}
theme root directory path code
<?php $root_path = get_home_path(); ?>
print "Path: ".$root_path;
Return "Path: /var/www/htdocs/" or "Path: /var/www/htdocs/wordpress/" if it is subfolder
Theme Root Path
$theme_root = get_theme_root();
echo $theme_root
Results:- /home/user/public_html/wp-content/themes