How to Add a File Upload Option to WooCommerce Registration Form
Adding a file upload field to your WooCommerce registration form can be essential for gathering necessary documents or images from users. With a few lines of custom code, you can integrate this feature easily. This tutorial walks you through the process of adding the file upload field, validating the file, and saving it to the user’s profile.
Step 1: Insert File Upload Field
To add a file upload field to the WooCommerce registration form, use the following code in your theme’s functions.php
file. This will create a file input field where users can upload images, PDFs, or documents:
function custom_registration_file_upload() { ?> <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', 'custom_registration_file_upload');
Step 2: Validate the Uploaded File
Next, we need to ensure that the file is uploaded successfully and is of the correct type. Use this code to validate the uploaded file:
function validate_file_upload($errors, $username, $email) { if (isset($_FILES['file_upload']) && !empty($_FILES['file_upload']['name'])) { $upload_file = $_FILES['file_upload']; if ($upload_file['error'] !== UPLOAD_ERR_OK) { $errors->add('file_upload_error', __('File upload failed. Please try again.', 'text-domain')); } } return $errors; } add_filter('woocommerce_registration_errors', 'validate_file_upload', 10, 3);
Step 3: Save File to User Profile
Once the file is validated, the next step is to save it to the user’s profile. Use the following code to save the uploaded file path to the WordPress user meta:
function save_uploaded_file($user_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($user_id, 'user_uploaded_file', $file_path); } } add_action('woocommerce_created_customer', 'save_uploaded_file');
Conclusion
By following these simple steps, you can easily integrate a file upload field in the WooCommerce registration form. This feature can be useful for collecting documents, profile pictures, or other essential files from your customers.
If you’re looking for more customization options, explore the WooCommerce documentation for additional features.