Woocommerce Update User Profile with Upload Photo
Hello mates, it's been awhile since my last share.
Anyway, what I'm about to share is a simple trick to add a feature in woocommerce update user profile page with upload photo/avatar.
Open up the functions.php from your theme and start adding the code below.
First step is to add an html attribute to make the form pass the file type fields
add_action('woocommerce_edit_account_form_tag',function(){ echo ' enctype="multipart/form-data"'; });
Second step is to add the field at the very top of the form
add_action('woocommerce_edit_account_form_start',function(){ ?> <p><label for="photo">Photo</label><input type="file" id="photo" name="photo" /></p> <?php });
Third step is to upload the photo and save it as user meta
add_action('woocommerce_save_account_details',function( $user_id ){ if ( ! function_exists( 'wp_handle_upload' ) ) { require_once( ABSPATH . 'wp-admin/includes/file.php' ); } $uploadedfile = $_FILES['photo']; $movefile = wp_handle_upload( $uploadedfile, array('test_form' => FALSE) ); if ( $movefile && !isset( $movefile['error'] ) ) { update_user_meta($user_id, 'avatar', $movefile['url']) or add_user_meta($user_id, 'avatar', $movefile['url']); } else { echo $movefile['error']; } });
Fourth Step is to override the avatar using filter
add_filter ('get_avatar', function($avatar_html, $id_or_email, $size, $default, $alt) { $avatar = get_user_meta($id_or_email,'avatar',true); if( $avatar ) { return '<img src="'.$avatar.'" width="96" height="96" alt="Avatar" class="avatar avatar-96 wp-user-avatar wp-user-avatar-96 photo avatar-default" />'; } else { return $avatar_html; } }, 10, 5);
That's it, uploading a photo or avatar feature has been added woocommerce website!