61
You can add first and last name to the WooCommerce registration form (easy, no?). Or maybe a custom radio field. And why not, a file upload input – which is able to load an image from the user’s browser, assign it to the form, and add the image to “Media” in your WordPress install.
And today we’ll see exactly that. Unfortunately the “woocommerce_form_field” function does not allow (yet, maybe) to generate file input fields, so we’ll just use basic HTML. Enjoy!
PHP Snippet: Add File Upload Field @ WooCommerce My Account Registration
/**
* @snippet File Upload @ WooCommerce My Account Registration
* @how-to Get tutoraspire.com FREE
* @author Tutor Aspire
* @compatible WooCommerce 3.7
* @donate $9 https://tutoraspire.com
*/
// --------------
// 1. Add file input to register form
add_action( 'woocommerce_register_form', 'tutoraspire_add_woo_account_registration_fields' );
function tutoraspire_add_woo_account_registration_fields() {
?>
add( 'image_error', __( 'Please provide a valid image', 'woocommerce' ) );
}
return $errors;
}
// --------------
// 3. Save new field
add_action( 'user_register', 'tutoraspire_save_woo_account_registration_fields', 1 );
function tutoraspire_save_woo_account_registration_fields( $customer_id ) {
if ( isset( $_FILES['image'] ) ) {
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attachment_id = media_handle_upload( 'image', 0 );
if ( is_wp_error( $attachment_id ) ) {
update_user_meta( $customer_id, 'image', $_FILES['image'] . ": " . $attachment_id->get_error_message() );
} else {
update_user_meta( $customer_id, 'image', $attachment_id );
}
}
}
// --------------
// 4. Add enctype to form to allow image upload
add_action( 'woocommerce_register_form_tag', 'tutoraspire_enctype_custom_registration_forms' );
function tutoraspire_enctype_custom_registration_forms() {
echo 'enctype="multipart/form-data"';
}