Upload Files Programmatically In WordPress

WordPress as a CMS allows environment or feature to uploads files, images through media uploader. But what if someone wants to upload files programmatically in WordPress?

As a PHP Developer, we know the method move_uploaded_file() which use to upload files on a server. But, when it comes to WordPress use of this PHP function is not recommended. We should use the function provided by WordPress for file uploading which is wp_upload_bits().

Benefit Of Using Method wp_upload_bits()

All uploaded files through media uploader getting stored under the ‘wp-content/uploads’ directory. And if we are planning to upload files programmatically in WordPress, those files also should store under the same uploads folder. It is a standard practice for WordPress.

When we use the method wp_upload_bits(), it will automatically store our uploaded file in the ‘wp-content/uploads’ directory. We don’t need to externally specify a target directory. Also, after uploading a file through this method, it returns both relative and absolute path of uploaded file.

Code To Upload Files Programmatically In WordPress

As mentioned on documentation of wp_upload_bits(), this function actually does not move the file to the upload folder. Instead it will create a new file with the content in $bits parameter.

Use of this method is really simple. Let’s say you have one file input in your form.

<input type="file" name="image" />

For the above file input, you need write the below code for uploading a file.

wp_upload_bits($_FILES['image']['name'], null, $_FILES['image']['tmp_name']);

Above code will perform following tasks for you.

  • Create your uploaded file under wp-content/uploads directory.
  • Give unique filename for your uploaded file.
  • Return absolute and relative path of your uploaded file.

If you are a keen developer and want to look how WordPress defined wp_upload_bits() function then you can see core functions.php file here.

I hope you understand how to upload files programmatically in WordPress. If you have any questions or suggestions please leave a comment below.

If you liked this article, then please subscribe to our Youtube Channel for video tutorials.

Recommended Tutorials For You

Leave a Reply

Your email address will not be published. Required fields are marked *