wp_mkdir_p()
Recursively creates a directory (folder) at the specified path. Does nothing if the folder already exists. Grants parent permissions to new folders.
This is a wrapper for the basic PHP function mkdir().
- The function cleans the provided path, removing any possible double slashes //.
- Preserves the protocol, for example
file://. - Created folders inherit parent permissions.
- The path cannot contain
../- in this case, the directory will not be created.
See also: WP_Filesystem_Direct{}.
1 time — 0.0002389 sec (fast) | 50000 times — 0.16 sec (very fast) | PHP 7.3.3, WP 5.2.3
No Hooks.
Returns
true|false. Whether the specified directory was created. true will also be returned if the folder already exists.
Usage
wp_mkdir_p( $target );
- $target(string) (required)
- Full path to the directory that needs to be created.
Examples
#1 Directory Creation Demo
Suppose we need to create a nested directories:
if ( wp_mkdir_p( 'a/really/deep/sub/directory' ) ){
echo 'Directory created!';
} #2 Creating a directory inside /uploads
This example shows how to create a new folder in the /uploads directory, while activating the plugin.
It can be useful when the plugin has file import functions or the ability to upload files and you want to save all files to a specific folder.
function myplugin_activate() {
$upload = wp_upload_dir();
$upload_dir = $upload['basedir'] . '/mypluginfiles';
if ( ! wp_mkdir_p( $upload_dir ) ){
echo "Failed to create mypluginfiles directory";
}
}
register_activation_hook( __FILE__, 'myplugin_activate' );
Changelog
| Since 2.0.1 | Introduced. |