函数文档

path_join()

💡 云策文档标注

概述

path_join() 函数用于连接两个文件系统路径,如果第二个路径是绝对路径,则直接返回该路径,否则将其与基础路径拼接。

关键要点

  • 函数接受两个参数:$base(基础路径)和 $path(相对路径),均为字符串类型且必需
  • 如果 $path 是绝对路径(通过 path_is_absolute() 检测),函数直接返回 $path
  • 否则,函数返回拼接后的路径,格式为 rtrim($base, '/') . '/' . $path
  • 返回值类型为字符串,表示拼接后的路径或绝对路径

代码示例

function path_join( $base, $path ) {
	if ( path_is_absolute( $path ) ) {
		return $path;
	}

	return rtrim( $base, '/' ) . '/' . $path;
}

注意事项

  • 函数自 WordPress 2.5.0 版本引入
  • 相关函数包括 path_is_absolute(),用于检测路径是否为绝对路径
  • 该函数被多个核心函数调用,如 wp_get_original_image_path()、wp_delete_attachment_files() 等,主要用于处理文件路径操作

📄 原文内容

Joins two filesystem paths together.

Description

For example, ‘give me $path relative to $base’. If the $path is absolute, then it the full path is returned.

Parameters

$basestringrequired
Base path.
$pathstringrequired
Path relative to $base.

Return

string The path with the base or absolute path.

Source

function path_join( $base, $path ) {
	if ( path_is_absolute( $path ) ) {
		return $path;
	}

	return rtrim( $base, '/' ) . '/' . $path;
}

Changelog

Version Description
2.5.0 Introduced.