_wp_get_attachment_relative_path()
云策文档标注
概述
_wp_get_attachment_relative_path() 函数用于获取附件文件相对于上传目录的路径。它处理文件路径,返回相对路径字符串,并兼容旧版本上传。
关键要点
- 参数:$file(字符串,必需),表示附件文件名。
- 返回值:字符串,附件相对于上传目录的路径。
- 功能:通过 dirname() 获取目录名,处理 '.' 和 'wp-content/uploads' 子串以生成相对路径。
- 兼容性:支持 WordPress 2.7 之前的旧上传路径。
代码示例
function _wp_get_attachment_relative_path( $file ) {
$dirname = dirname( $file );
if ( '.' === $dirname ) {
return '';
}
if ( str_contains( $dirname, 'wp-content/uploads' ) ) {
// Get the directory name relative to the upload directory (back compat for pre-2.7 uploads).
$dirname = substr( $dirname, strpos( $dirname, 'wp-content/uploads' ) + 18 );
$dirname = ltrim( $dirname, '/' );
}
return $dirname;
}
原文内容
Gets the attachment path relative to the upload directory.
Parameters
$filestringrequired-
Attachment file name.
Source
function _wp_get_attachment_relative_path( $file ) {
$dirname = dirname( $file );
if ( '.' === $dirname ) {
return '';
}
if ( str_contains( $dirname, 'wp-content/uploads' ) ) {
// Get the directory name relative to the upload directory (back compat for pre-2.7 uploads).
$dirname = substr( $dirname, strpos( $dirname, 'wp-content/uploads' ) + 18 );
$dirname = ltrim( $dirname, '/' );
}
return $dirname;
}
Changelog
| Version | Description |
|---|---|
| 4.4.1 | Introduced. |