WooCommerce : Upload File in My Account Registration Form.

How to upload profile picture or any file during WooCommerce My Account Registration?

For uploading file from WooCommerce My Account Registration form we need to set form enctype type To multipart/form-data.secondly , we need to add html tags for input type file to upload file. then we need to validate them if the field field is required.Finally after upload file enter media id to user meta.

For uploading files may be image or other files in WooCommerce Registration form. We should follow these steps

  1. Make form enctype type To multipart/form-data
  2. We have to add html of input type file in form
  3. Than we have to validate these fields
  4. Than Finally Upload File and save field to User meta

Step 1 : We have to use ‘woocommerce_register_form_tag’ Hook.

// Add enctype to form to allow file upload
function AddEnctypeCustomRegistrationForms() {
  echo 'enctype="multipart/form-data"';
}
add_action('woocommerce_register_form_tag','AddEnctypeCustomRegistrationForms');

Step 2 : We have to use ‘woocommerce_register_form’ Hook.

// Add file input html to register form
add_action('woocommerce_register_form','AddImageField');
function AddImageField() {   
  ?>    
    <p class="form-row validate-required" id="pro_image" data-priority="">
    <label for="pro_image" class="">Image (JPG, PNG, PDF)<abbr class="required" title="required">*</abbr></label>
    <span class="woocommerce-input-wrapper">
      <input type='file' name='pro_image' accept='image/*,.pdf' required>
    </span>
    </p> 
  <?php       
}

Step 3: We have to use ‘woocommerce_registration_errors’ Hook.

// Validate new fields
function ValidateImageField( $errors, $username, $email ) {
  if ( isset( $_POST['pro_image'] ) && empty( $_POST['pro_image'] ) ) {
    $errors->add('pro_image_error', __( 'Please provide a valid image', 'woocommerce' ) );
  }
  return $errors;
}
add_filter('woocommerce_registration_errors','ValidateImageField',10,3 );

Step 4: We have to use ‘user_register’ Hook.

// Save new field
function SaveImageField( $customer_id ) {
  if ( isset( $_FILES['pro_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' );
    $attach_id= media_handle_upload('pro_image', 0 );
    if ( is_wp_error( $attach_id) ) {
      update_user_meta( $customer_id,'pro_image', $_FILES['pro_image'] . ": " . $attach_id->get_error_message() );
    } else {
      update_user_meta( $customer_id,'pro_image', $attach_id);
    }
  }
}
add_action('user_register','SaveImageField',1);

null

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top