Posted by

Woocommerce Update User Profile with Upload Photo

Woocommerce allows customers to update their profile information but updating their user profile photo is not included. This post will add that feature to your woocommerce website!

Just add these code snippets into theme’s functions.php

This is to make the woocommerce form to upload a file.

add_action('woocommerce_edit_account_form_tag',function(){
	echo ' enctype="multipart/form-data"';
});

Second is to add the upload photo field in 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 is the function that will process to save the uploaded photo. Please note that you still need to add a validation to only accept image.

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'];
	}
});

Our final step is to overwrite 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! You have now an upload photo feature in your woocommerce website!