ACF Upload Image in front-end with custom form

Ok, I got it to work with the ‘media_handle_upload’ (pointed out by @Piyush) and tweaking a little bit with my form code.

So, here is what I did:

First – Make sure your form has the attribute ‘enctype=”multipart/form-data”.

Second – Be sure that your ‘input=file’ has no value attribute.

Third – Use the ‘media_handle_upload’ and pass the name of your ‘input=file’.

Forth – Check if there was an error with ‘is_wp_error’, for example.

Fifth – Update the user meta using the name of the field you want to update (in my case, is the same as the ‘name’ of the ‘input=file’.

Here is part of the final code:

<form method="post" id="adduser" enctype="multipart/form-data">
    <input class="text-input" name="avatar_user" type="file" id="avatar_user" multiple="false"/>
    <input name="updateuser" type="submit" id="updateuser" class="submit button" value="<?php _e('GRAVAR', 'profile'); ?>" />
    <input name="action" type="hidden" id="action" value="update-user" />
</form>

/* If profile was saved, update profile. */
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == 'update-user' ) {

    // 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.
    $img_id = media_handle_upload( 'avatar_user', 0 );

    if ( is_wp_error( $img_id ) ) {
      echo "Error";
    } else {
      update_user_meta( $current_user->ID, 'avatar_user', $img_id );
    }
}

Leave a Comment