Most times in theme option or in plugins we give option to upload files. WordPress wp_handle_upload() function makes it easy to upload these files. Function wp_handle_upload() has proper error handling and uploads file to current month upload directory.
WordPress uses this function to upload media, upload import file, upload header background and upload background image. In this post I will show how to use wp_handle_upload().
<?php $overrides = array( 'test_form' => false); $file=wp_handle_upload($_FILES['rt_file'], $overrides); ?>
wp_handle_upload() accepts two parameters. $_FILES[‘rt_file’] is single element of $_FILES and the second parameter is array to override default file upload options. Parameter $overrides is optional but always set $overrides with value test_form=false else it will return form submission error.
On success wp_handle_upload() returns an associative array of file attributes. The returned array has the absolute path of an uploaded file, URL of an uploaded file & type of uploaded file.
On failure wp_handle_upload() returns array which has error message.
We can use our own error handling function by passing function name in $overrides[‘upload_error_handler’] as shown below:
$overrides = array( 'test_form' => false,'upload_error_handler' =>rt_handle_upload_error );
‘rt_handle_upload_error’ is our defined function to handle upload error.
There is no need to override default wp_handle_upload options except test_form.
You can add more mime types for upload using upload_mimes filter.
You will find wp_handle_upload() in wp-admin/includes/file.php.
Hope it helps handling uploading files in WordPress. 🙂 Feel free to share your views or queries through your comments.