The media_handle_upload() WordPress PHP function saves a file submitted from a POST request and creates an attachment post for it.
Usage
media_handle_upload( $file_id, $post_id, $post_data = array(), $overrides = array( 'test_form' => false ) );
Parameters
$file_id(string) – Index of the $_FILES array that the file was sent.$post_id(int) – The post ID of a post to attach the media item to. Required, but can be set to 0, creating a media item that has no relationship to a post.$post_data(array) – Optional. Overwrite some of the attachment. Default: array()$overrides(array) – Optional. Override the wp_handle_upload() behavior. Default: array(‘test_form’ => false)
More information
See WordPress Developer Resources: media_handle_upload()
Examples
Upload a file from a form
This example demonstrates how to upload a file from a form and attach it to a post with ID 123.
Form:
<form id="featured_upload" method="post" action="#" enctype="multipart/form-data"> <input type="file" name="my_image_upload" id="my_image_upload" /> <input type="submit" name="submit_image" value="Upload" /> </form>
PHP:
if ( isset( $_POST['submit_image'] ) ) {
$uploaded_file_id = media_handle_upload( 'my_image_upload', 123 );
}
Upload a file and create a standalone media item
This example demonstrates how to upload a file without associating it with any post (by setting the post ID to 0).
if ( isset( $_POST['submit_image'] ) ) {
$uploaded_file_id = media_handle_upload( 'my_image_upload', 0 );
}
Overwrite attachment properties
This example demonstrates how to overwrite some of the attachment properties, such as the title and description.
if ( isset( $_POST['submit_image'] ) ) {
$post_data = array(
'post_title' => 'Custom Title',
'post_content' => 'Custom Description',
);
$uploaded_file_id = media_handle_upload( 'my_image_upload', 123, $post_data );
}
Customize the uploaded file name
This example demonstrates how to customize the uploaded file’s name using the $overrides parameter.
if ( isset( $_POST['submit_image'] ) ) {
$overrides = array(
'unique_filename_callback' => function ( $dir, $name, $ext ) {
return 'custom_name' . $ext;
},
);
$uploaded_file_id = media_handle_upload( 'my_image_upload', 123, array(), $overrides );
}
Allow only certain file types
This example demonstrates how to restrict the allowed file types for the uploaded files.
if ( isset( $_POST['submit_image'] ) ) {
$overrides = array(
'test_form' => false,
'mimes' => array(
'jpg|jpeg|jpe' => 'image/jpeg',
'png' => 'image/png',
),
);
$uploaded_file_id = media_handle_upload( 'my_image_upload', 123, array(), $overrides );
}