函数文档

_wp_relative_upload_path()

💡 云策文档标注

概述

_wp_relative_upload_path() 函数用于获取上传文件的相对路径,相对于当前上传目录。它接受一个完整文件路径作为参数,并返回相对路径或失败时返回原路径。

关键要点

  • 函数返回上传文件的相对路径,基于当前上传目录(通过 wp_get_upload_dir() 获取)。
  • 参数 $path 是必需的字符串,表示文件的完整路径。
  • 返回值:成功时返回相对路径字符串,失败时返回未更改的原路径。
  • 包含一个过滤器 _wp_relative_upload_path,允许开发者修改相对路径。
  • 函数在 WordPress 2.9.0 版本中引入。

代码示例

function _wp_relative_upload_path( $path ) {
    $new_path = $path;

    $uploads = wp_get_upload_dir();
    if ( str_starts_with( $new_path, $uploads['basedir'] ) ) {
        $new_path = str_replace( $uploads['basedir'], '', $new_path );
        $new_path = ltrim( $new_path, '/' );
    }

    /**
     * Filters the relative path to an uploaded file.
     *
     * @since 2.9.0
     *
     * @param string $new_path Relative path to the file.
     * @param string $path     Full path to the file.
     */
    return apply_filters( '_wp_relative_upload_path', $new_path, $path );
}

注意事项

  • 函数依赖于 wp_get_upload_dir() 获取上传目录信息,确保上传目录已正确设置。
  • 如果路径不以基于目录开头,函数将返回原路径,这可能表示路径无效或不在上传目录内。
  • 过滤器 _wp_relative_upload_path 可用于自定义相对路径逻辑,例如处理子目录或特殊文件结构。

📄 原文内容

Returns relative path to an uploaded file.

Description

The path is relative to the current upload dir.

Parameters

$pathstringrequired
Full path to the file.

Return

string Relative path on success, unchanged path on failure.

Source

function _wp_relative_upload_path( $path ) {
	$new_path = $path;

	$uploads = wp_get_upload_dir();
	if ( str_starts_with( $new_path, $uploads['basedir'] ) ) {
			$new_path = str_replace( $uploads['basedir'], '', $new_path );
			$new_path = ltrim( $new_path, '/' );
	}

	/**
	 * Filters the relative path to an uploaded file.
	 *
	 * @since 2.9.0
	 *
	 * @param string $new_path Relative path to the file.
	 * @param string $path     Full path to the file.
	 */
	return apply_filters( '_wp_relative_upload_path', $new_path, $path );
}

Hooks

apply_filters( ‘_wp_relative_upload_path’, string $new_path, string $path )

Filters the relative path to an uploaded file.

Changelog

Version Description
2.9.0 Introduced.