How To Upload Files From The Front End In WordPress With Media_Handle_Upload
Use media_handle_upload() to accept a file from a form on your site and add it to the Media Library. WordPress validates the file type, moves the file and creates the attachment and the image sizes for you.
HTML form
<form method="post" enctype="multipart/form-data" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
<?php wp_nonce_field( 'lotgrafix_upload', 'lotgrafix_upload_nonce' ); ?>
<input type="hidden" name="action" value="lotgrafix_upload">
<input type="file" name="lotgrafix_file" accept="image/*,application/pdf" required>
<button type="submit">Upload</button>
</form>
Handler
This version is for logged in users only.
php">function lotgrafix_handle_upload() {
check_admin_referer( 'lotgrafix_upload', 'lotgrafix_upload_nonce' );
if ( ! current_user_can( 'upload_files' ) ) {
wp_die( esc_html__( 'Not allowed.', 'lotgrafix' ), '', array( 'response' => 403 ) );
}
if ( empty( $_FILES['lotgrafix_file']['name'] ) ) {
wp_die( esc_html__( 'No file selected.', 'lotgrafix' ) );
}
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
$lotgrafix_id = media_handle_upload( 'lotgrafix_file', 0 );
if ( is_wp_error( $lotgrafix_id ) ) {
wp_die( esc_html( $lotgrafix_id->get_error_message() ) );
}
wp_safe_redirect( add_query_arg( 'uploaded', $lotgrafix_id, wp_get_referer() ) );
exit;
}
add_action( 'admin_post_lotgrafix_upload', 'lotgrafix_handle_upload' );
The second argument is the ID of the post to attach the file to. Use 0 for no parent.
Allow only specific file types
function lotgrafix_allowed_mimes( $mimes ) {
return array_intersect_key( $mimes, array_flip( array( 'jpg|jpeg|jpe', 'png', 'pdf' ) ) );
}
add_filter( 'upload_mimes', 'lotgrafix_allowed_mimes' );
This filter affects the whole site, including the admin. Add a condition if you only want it for your form.
Change the maximum upload size
function lotgrafix_upload_limit( $size ) {
return 5 * MB_IN_BYTES;
}
add_filter( 'upload_size_limit', 'lotgrafix_upload_limit' );
Security tips
- Never accept uploads from anonymous visitors without strict limits on file type and size.
- Do not allow SVG or PHP related file types unless you sanitize them.
- Always verify the nonce and the user capability.


