WordPress Code Snippets

A fresh mix of code snippets and tutorials

WordPress Create Upload Files and Directories


This tutorial explains how to create new files and directories in the WordPress /uploads/ folder.

Create new file in the uploads directory

WordPress provides the function wp_upload_bits() to create a new file in the /uploads/ directory. Here is a quick example showing possible usage:

In this example, we assume a file input named image. Upon form submission, this code attempts to save a copy of the image to the WordPress /uploads/ directory.

The function wp_upload_bits() performs basic security checks for the uploaded file and includes any errors in the return array, $upload. The $upload array also includes the file system path and the URL of the uploaded file.

Note that PHP automatically deletes the temp file so there is no need for special treatment in that regard. Refer to the Codex for more details (see footer references).

Create new subdirectory in the uploads directory

To create directories in WordPress, we can use the WP function wp_mkdir_p(). This function may be used to create directories just about anywhere, but when using to create subdirectories in the /uploads/ directory, it’s helpful also to use wp_upload_dir() to get the necessary path information.

To give you a better idea, here is a simple example provided by the WP Codex:

This code gets the required information about the uploads directory and uses it to create a subdirectory via wp_mkdir_p(). Alternately we can use the PHP function mkdir, as demonstrated in the following example:

Here we also are using wp_upload_dir() to retrieve the required information about the /uploads/ directory. FWIW, I use a variation of this technique in my plugin, USP Pro (User Submitted Posts Pro).


The techniques here probably are best for quick implementations and smaller projects. For more extensive/advanced file implementations, check out WP’s Filesystem API. Thanks to @eliorivero for the heads up!


Learn more

WordPress Themes In Depth

Show Support

Like our new Facebook Page to show support!