Using WordPress ‘wp_mkdir_p()’ PHP function

The wp_mkdir_p() WordPress PHP function is designed to create directories recursively based on a complete path. It can also set permissions on these folders.

Usage

A simple example of the function:

$targetPath = '/your/desired/path';
if ( wp_mkdir_p( $targetPath ) ) {
echo __( 'Directory successfully created!', 'textdomain' );
}

In this snippet, the function attempts to create a directory at the location specified by $targetPath. If successful, it outputs a message.

Parameters

  • $target (string, Required): The full path of the directory that the function will attempt to create.

More information

See WordPress Developer Resources: wp_mkdir_p() This function is an integral part of the WordPress core and is not deprecated as of the latest version.

Examples

Creating a Deep Sub-directory

Suppose you want to create a sub-directory that’s several levels deep, you can use this function:

$targetPath = '/a/very/deep/sub/directory';
if ( wp_mkdir_p( $targetPath ) ) {
echo __( 'Sub-directory successfully created!', 'textdomain' );
}

This code attempts to create a deeply nested sub-directory at the path specified in $targetPath.

Setting Permissions to 777 for a Cache Folder

To create a directory with full permissions (777), useful for a cache folder:

$cache_folder = ABSPATH . 'cache';
if ( ! is_dir( $cache_folder ) ) {
wp_mkdir_p( $cache_folder );
chmod( $cache_folder, 0777 );
}

This code checks if a directory named ‘cache’ exists in the root directory of your WordPress installation. If it doesn’t, the function creates it and sets its permissions to 777.

Checking if a Directory Exists

To create a directory only if it doesn’t already exist:

$folder = ABSPATH . 'my-folder';
if ( ! is_dir( $folder ) ) {
wp_mkdir_p( $folder );
}

This script checks if a directory named ‘my-folder’ exists in the root directory of your WordPress installation. If it doesn’t, the function creates it.

Creating a Directory for User Uploads

If you want to create a directory for each user to upload files, you can do it as follows:

$user_id = get_current_user_id();
$uploads_dir = wp_upload_dir();
$user_folder = $uploads_dir['basedir'] . '/' . $user_id;

if ( ! is_dir( $user_folder ) ) {
wp_mkdir_p( $user_folder );
}

This script creates a new directory in the WordPress uploads directory for the current user, identified by their user ID.

Handling Failed Directory Creation

To gracefully handle situations where directory creation fails:

$new_folder = ABSPATH . 'new-folder';

if ( ! wp_mkdir_p( $new_folder ) ) {
echo __( 'Directory creation failed. Please check your permissions.', 'textdomain' );
}

In this example, if the function fails to create the ‘new-folder’, it echoes an error message prompting the user to check their permissions.