Upload file from front end to media admin in wordpress

Upload file from front end to media admin in wordpress

In this article I will show you: How to upload file from front end to media admin in wordpress.

Step 1: Creating HTML Form

<form action="" method="POST" enctype="multipart/form-data">
	<div class="form-group">
		<label>Upload File</label>
		<div class="input-group">
			<input type="file" name="file_upload" class="uploadfile">
		</div>
	</div>
	<div class="form-group">
		<label>&nbsp;</label>
		<div class="input-group">
			<input type="hidden" name="upload" value="1" />
			<input type="submit" value="Submit">
		</div>
	</div>
</form>

Step 2: Submit and save file to media admin

if ( isset($_POST['upload'])) {
	if($_FILES["file_upload"]["error"] != 4){
		// These files need to be included as dependencies when on the front end.
		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 upload.
		// Remember, 'file_upload' is the name of our file input in our form above.
		$attachment_id = media_handle_upload( 'file_upload', 0 );
		
		if ( is_wp_error( $attachment_id ) ) {
			// There was an error uploading the image.
			echo '<div class="error"><p>There was an error uploading </p></div>';
		} else {
			// The image was uploaded successfully!
			$link_file = wp_get_attachment_url( $attachment_id );
			echo '<div id="message" style="margin: 0;" class="notice is-dismissible">
	                    <p>File uploaded. </p></div>';
		}
	}
	else{
		echo '<div class="error"><p>there is no file uploaded</p></div>';
	}
	
}

Comments

comments

Share