get_home_path()
云策文档标注
概述
get_home_path() 函数用于获取 WordPress 安装根目录的绝对文件系统路径。它通过比较 home 和 siteurl 选项,结合服务器脚本路径计算得出,适用于后台管理场景。
关键要点
- 返回 WordPress 安装根目录的完整文件系统路径字符串
- 函数定义在 wp-admin/includes/file.php 中,默认仅在后台页面可用
- 使用时需确保文件已包含,否则可能引发未定义函数错误
- 在 WP_CLI 环境下可能返回不正确结果,需注意兼容性
代码示例
// 返回路径如 "/var/www/htdocs/" 或子文件夹路径
printf( 'Path: %s', get_home_path() );
// 确保 get_home_path() 已声明
require_once ABSPATH . 'wp-admin/includes/file.php';
$home_path = get_home_path();注意事项
- 该函数仅在后端(wp-admin)可用,前端使用前需检查 is_admin()
- 在 WP_CLI 中可能无法正确工作,建议测试验证
- 依赖 set_url_scheme()、trailingslashit() 和 get_option() 等辅助函数
原文内容
Gets the absolute filesystem path to the root of the WordPress installation.
Source
function get_home_path() {
$home = set_url_scheme( get_option( 'home' ), 'http' );
$siteurl = set_url_scheme( get_option( 'siteurl' ), 'http' );
if ( ! empty( $home ) && 0 !== strcasecmp( $home, $siteurl ) ) {
$wp_path_rel_to_home = str_ireplace( $home, '', $siteurl ); /* $siteurl - $home */
$pos = strripos( str_replace( '\', '/', $_SERVER['SCRIPT_FILENAME'] ), trailingslashit( $wp_path_rel_to_home ) );
$home_path = substr( $_SERVER['SCRIPT_FILENAME'], 0, $pos );
$home_path = trailingslashit( $home_path );
} else {
$home_path = ABSPATH;
}
return str_replace( '\', '/', $home_path );
}
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 4 content
Codex
Default Usage
// Return "Path: /var/www/htdocs/" or "Path: /var/www/htdocs/wordpress/" if it is subfolder. printf( 'Path: %s', get_home_path() );Skip to note 5 content
Malcure Web Security
Apparently this doesn’t return the correct results when using WP_CLI.
Skip to note 6 content
Rolf Allard van Hagen
Note that
get_home_path()is declared in wp-admin/includes/file.php which is not included by default, except on admin pages when wp-admin/includes/admin.php has been included.// Ensure get_home_path() is declared. require_once ABSPATH . 'wp-admin/includes/file.php'; $home_path = get_home_path();