media_handle_upload(): Process Image and File Uploads in WordPress

Handling uploaded files can be a nuisance in application development. In WordPress, that is not the case. WordPress provides the function media_handle_upload for processing uploaded images and files. We only need to pass the required arguments to the function, and the uploaded image or file will be saved on the server automatically and inserted into the Media Library. Let us look at how to use this function.

media_handle_upload parameters

Parameter Type Required Default Description
$file_id string Required The index in PHP’s $_FILES superglobal.
$post_id int Optional 0 The post ID the uploaded file should be attached to.
$post_data array Optional null Allows you to modify some attachment fields.
$overrides array Optional [] Allows you to override the behavior of wp_handle_upload().

Return value

(int|WP_Error)
Returns the attachment ID on success, or a WP_Error instance on failure.

Example

Front-end form

<form id="featured_upload" method="post" action="#" enctype="multipart/form-data">
	<input type="file" name="my_image_upload" id="my_image_upload"  multiple="false" />
	<input type="hidden" name="post_id" id="post_id" value="55" />
	<?php wp_nonce_field( 'my_image_upload', 'my_image_upload_nonce' ); ?>
	<input id="submit_my_image_upload" name="submit_my_image_upload" type="submit" value="Upload" />
</form>

Process the uploaded file

// Check the nonce and user capability
if (
	isset( $_POST['my_image_upload_nonce'], $_POST['post_id'] )
	&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
	&& current_user_can( 'edit_post', $_POST['post_id'] )
) {
	// If the checks pass, the request is safe

	// When used on the front end, include these three files
	require_once( ABSPATH . 'wp-admin/includes/image.php' );
	require_once( ABSPATH . 'wp-admin/includes/file.php' );
	require_once( ABSPATH . 'wp-admin/includes/media.php' );
	
	// Let WordPress handle the uploaded file
	// Note: 'my_image_upload' is the name attribute of the file field above
	$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
	
	if ( is_wp_error( $attachment_id ) ) {
		// Handle the upload error
	} else {
		// Handle a successful upload
	}

} else {

	// Message to display when the nonce check fails
}

Related Posts

Leave a Reply

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