How to Create multiple File Upload Field on Checkout Page WooCommerce

How to Create multiple File Upload Field on Checkout Page WooCommerce
829 Views
1
(1)

Creating multiple file upload fields on the checkout page of a WooCommerce site allows merchants to collect additional information from customers, which can be particularly useful for custom orders, personalized products, or when specific documentation is required.

This capability enhances the flexibility and functionality of WooCommerce, enabling a more tailored shopping experience. Implementing this feature involves custom coding to integrate the upload fields into the WooCommerce checkout process, handle the file uploads securely, and attach the uploaded files or their information to the customer’s order for reference and fulfillment purposes.

<?php
add_action( 'woocommerce_after_checkout_billing_form', 'cxc_checkout_page_file_upload_field' );
function cxc_checkout_page_file_upload_field() { 
	?>
	<style type="text/css">
		#cxc_file { border: 1px solid #ddd; padding: 10px; width: 100%; line-height: 30px; font-size: 13px; }
	</style>
	<div class="form-row form-row-wide">
		<input type="file" id="cxc_file" name="cxc_file[]" multiple />
		<input type="hidden" name="cxc_file_field" />
		<div id="cxc_filelist"></div>
	</div>
	<?php
}
?>
<?php
add_action('wp_ajax_cxc_checkout_file_upload', 'cxc_file_upload');
add_action('wp_ajax_nopriv_cxc_checkout_file_upload', 'cxc_file_upload');

function cxc_file_upload() {
	$upload_dir = wp_upload_dir();
	$image_urls = array();

	if (isset($_FILES['cxc_files'])) {
		$allowed_types = array('image/jpeg', 'image/png', 'image/gif');

		foreach ($_FILES['cxc_files']['name'] as $key => $value) {
			$file_type = $_FILES['cxc_files']['type'][$key];

			// Check if the file type is empty or not allowed
			if (empty($file_type) || !in_array($file_type, $allowed_types)) {
				wp_send_json(array('type' => 'error', 'message' => 'Invalid file type.'));
			}

			$path = $upload_dir['path'] . '/' . basename($value);

			if (move_uploaded_file($_FILES['cxc_files']['tmp_name'][$key], $path)) {
				$image_url = $upload_dir['url'] . '/' . basename($value);
				$image_urls[] = $image_url;
			} else {
				wp_send_json(array('type' => 'error', 'message' => 'Error uploading files.'));
			}
		}

		wp_send_json(array('type' => 'success', 'image_urls' => $image_urls));
	} else {
		wp_send_json(array('type' => 'error', 'message' => 'Files not found.'));
	}
}
?>
<?php
add_action( 'wp_footer', 'cxc_add_custom_js_checkout_image_upload' );

function cxc_add_custom_js_checkout_image_upload() {
	?>
	<script type="text/javascript">
		jQuery( function( $ ) {
			jQuery(document).on('change', '#cxc_file', function() {
				jQuery('.cxc-error').remove();
				if ( this.files.length === 0 ) {
					jQuery( '#cxc_filelist' ).empty();
				} else {
					const files = this.files;
					const formData = new FormData();
					for ( let i = 0; i < files.length; i++ ) {
						formData.append( 'cxc_files[]', files[i] );
					}

					jQuery.ajax({
						url: wc_checkout_params.ajax_url + '?action=cxc_checkout_file_upload',
						type: 'POST',
						data: formData,
						contentType: false,
						enctype: 'multipart/form-data',
						processData: false,
						success: function ( response ) {
							if( response ){
								if( response.type == 'success' ){
									jQuery.each(response.image_urls, function(index, imageUrl) {
										jQuery( '#cxc_filelist' ).append('<img src="' + imageUrl + '">');
									});
									jQuery( 'input[name="cxc_file_field"]' ).val(JSON.stringify(response.image_urls));
								} else {
									jQuery('#cxc_file').after('<div class="cxc-error" role="alert">' + response.message + '</div>');
								}
							}
						}
					});
				}
			} );
		} );
	</script>
	<?php
}
<?php
add_action( 'woocommerce_checkout_update_order_meta', 'cxc_file_field_save_added' );
function cxc_file_field_save_added( $order_id ){

	if( ! empty( $_POST[ 'cxc_file_field' ] ) ) {
		update_post_meta( $order_id, 'cxc_file_field', sanitize_text_field( $_POST[ 'cxc_file_field' ] ) );
	}

}
?>
<?php
add_action( 'woocommerce_checkout_process', 'cxc_validate_new_checkout_field' );
   function cxc_validate_new_checkout_field() {
   if ( empty( $_POST['cxc_file_field'] ) ) {
      wc_add_notice( 'Please upload your document picture', 'error' );
   }
}
?>
<?php
add_action( 'woocommerce_admin_order_data_after_order_details', 'cxc_order_meta_general' );
function cxc_order_meta_general( $order ){

	$files = get_post_meta( $order->get_id(), 'cxc_file_field', true );
	if( $files ) {
		$files_arr = json_decode($files);
		foreach ( $files_arr as $key => $file) {
			echo '<img class="cxc-order-img" style="max-width: 400px;width: 100%;height: auto; margin-top: 10px;" src="'. esc_url( $file ) .'" />';
		}
	}
}

?>

Also read: How to Create File Upload Field on Checkout Page WooCommerce

integrating multiple file upload fields into the WooCommerce checkout page significantly enhances the functionality and customization capabilities of your e-commerce platform. By following the outlined steps, you can provide a more personalized shopping experience, allowing customers to upload files directly during the checkout process.

This approach not only meets the specific needs of customers but also positions CodexCoach as a forward-thinking brand that leverages technology to improve customer satisfaction and streamline the order fulfillment process.

How useful was this blog?

Click on a star to rate it!

Average rating 1 / 5. Vote count: 1

No votes so far! Be the first to rate this blog.

As you found this blog useful...

Follow us on social media!

We are sorry that this blog was not useful for you!

Let us improve this blog!

Tell us how we can improve this blog?

By Subhash Katakiya

Hey Guys, My Self Subhash Katakiya. I am a resident of Gujarat. I have 2+ years of experience in full-stack web development. Currently, I am working in CodexCoach Company. In particular, I specialize in WooCommerce, plugins, and themes. So, read my blogs and learn full-stack web development skills with my guide.

Leave a comment

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