How to Enable File Uploads on WooCommerce User Registration
Allowing users to upload files during registration on your WooCommerce store can be an important feature, especially if you’re collecting documents or profile images. This tutorial will guide you through adding a file upload field, validating the file, and storing it in the user’s profile.
Step 1: Add a File Upload Field
First, you need to add the file upload field to the registration form. Use the following code in your theme’s functions.php
file. It will display the file upload field on the WooCommerce registration page:
function woo_file_upload_field() { ?> <p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide"> <label for="file_upload"><?php esc_html_e('Upload Your File', 'text-domain'); ?> <span class="required">*</span></label> <input type="file" class="input-file" name="file_upload" id="file_upload" accept=".pdf,.doc,.docx,.png,.jpg,.jpeg" required> </p> <?php } add_action('woocommerce_register_form', 'woo_file_upload_field');
Step 2: Validate the File Upload
Now, we need to validate that the file uploaded by the user is of the right type and is successfully uploaded. Add this code to validate the file:
function validate_woo_file_upload($errors, $username, $email) { if (isset($_FILES['file_upload']) && !empty($_FILES['file_upload']['name'])) { $file = $_FILES['file_upload']; if ($file['error'] !== UPLOAD_ERR_OK) { $errors->add('upload_error', __('File upload failed. Please try again.', 'text-domain')); } } return $errors; } add_filter('woocommerce_registration_errors', 'validate_woo_file_upload', 10, 3);
Step 3: Save the File to the User’s Profile
Once the file has been validated, you can save it to the user’s profile. Below is the code that moves the file to the WordPress upload directory and saves the file path as user meta:
function save_woo_file_upload($customer_id) { if (isset($_FILES['file_upload']) && !empty($_FILES['file_upload']['name'])) { $upload_dir = wp_upload_dir(); $file_name = $_FILES['file_upload']['name']; $file_tmp = $_FILES['file_upload']['tmp_name']; $file_path = $upload_dir['path'] . '/' . $file_name; move_uploaded_file($file_tmp, $file_path); update_user_meta($customer_id, 'profile_file', $file_path); } } add_action('woocommerce_created_customer', 'save_woo_file_upload');
Conclusion
By following these steps, you can easily enable file uploads on your WooCommerce registration form. This will allow users to submit files, such as documents or images, which will be saved securely to their profiles.
If you’re looking for more customization options, explore the WooCommerce documentation for additional features.