path_join()
Join two filesystem paths together. If the second parameter is an absolute path (starts with a slash), then only it will be returned.
It works this way: give me the $path relative to $base, but if the $path is absolute, then just return it.
Automatically adds a slash /
between the paths.
No Hooks.
Return
String
. The path with the base or absolute path.
Usage
path_join( $base, $path );
- $base(string) (required)
- Base path.
- $path(string) (required)
- Path relative to $base.
Examples
#1 Demo: examples of concatenating two paths
echo path_join( '/var/example.com', '/wp_content/uploads' ); //> /wp_content/uploads echo path_join( '/var/example.com', 'wp_content/uploads' ); //> /var/example.com/wp_content/uploads echo path_join( '/var/example.com', '' ); //> /var/example.com/ echo path_join( '/var/example.com', '\path' ); //> \path echo path_join( '/var/example.com', 'c:\path' ); //> c:\path
#2 Include a file
Suppose we don't know whether the path of the $file variable is an absolute path to the file or it just the file name (relative path). In this case it's convenient to use this function:
$path = path_join( '/var/site/wp-content/', $file ); require_once( $path );
Now, no matter what the $file variable is: file.php
or /var/site/wp-content/file.php
— in both cases $path variable will be /var/site/wp-content/file.php
.
#3 Demo of the gluing of the two tracks. [auto-translate]
echo path_join('/var/example.com', '/wp_content/uploads'); //> /wp_content/uploads echo path_join('/var/example.com', 'wp_content/uploads'); //> /var/example.com/wp_content/uploads echo path_join('/var/example.com', ''); //> /var/example.com/ echo path_join('/var/example.com', '\path'); //> \path echo path_join('/var/example.com', 'c:\path'); //> c:\path
#4 Connecting the file by checking it's path beforehand
Suppose we don't know beforehand how the file will be transferred: by absolute path or just its name. In this case, this function comes in handy. If the file name is specified, the base (path) will be added to it, if the full path of the file is specified, nothing will be added and the full path will be taken:
$path = path_join( '/var/site/wp-content/', $file ); require_once( $path );
Now, $file can be file.php
or /var/site/wp-content/file.php
. In both cases the path to the file will be returned: /var/site/wp-content/file.php
Changelog
Since 2.5.0 | Introduced. |
path_join() path join code WP 6.7.2
function path_join( $base, $path ) { if ( path_is_absolute( $path ) ) { return $path; } return rtrim( $base, '/' ) . '/' . $path; }