How to Create File Upload Field on Checkout Page WooCommerce

How to Create File Upload Field on Checkout Page WooCommerce
1530 Views
3.6
(984)

WooCommerce is the world’s most popular eCommerce platform. It is the top choice for many business owners when it comes to developing an online store, and for good reason.

Instead of keeping the transaction pending until they give you extra documents through email, you may allow your clients to upload files during the checkout process and finalize the sale immediately.

Why add a custom upload field in WooCommerce?

Some online ticketing providers demand passengers upload their ID or passport during the booking process. If you need to modify your ticket, request a refund, or seek compensation for a delay, the firm may require you to provide papers such as your passport or ID, the ticket you purchased, and so on.

<?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" />
		<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_url = '';

	if (isset($_FILES['cxc_file'])) {
        // Validate file type
		$allowed_types = array('image/jpeg', 'image/png', 'image/gif');
		$file_type = $_FILES['cxc_file']['type'];

		if (in_array($file_type, $allowed_types)) {
			$path = $upload_dir['path'] . '/' . basename($_FILES['cxc_file']['name']);

			if (move_uploaded_file($_FILES['cxc_file']['tmp_name'], $path)) {
				$image_url = $upload_dir['url'] . '/' . basename($_FILES['cxc_file']['name']);
				wp_send_json(array('type' => 'success', 'image_url' => $image_url));
			} else {
				wp_send_json(array('type' => 'error', 'message' => 'Error uploading file.'));
			}
		} else {
			wp_send_json(array('type' => 'error', 'message' => 'Invalid file type.'));
		}
	} else {
		wp_send_json(array('type' => 'error', 'message' => 'File 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 ) {
					jQuery( '#cxc_filelist' ).empty();
				} else {
					const file = this.files[0];
					const formData = new FormData();
					formData.append( 'cxc_file', file );

					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( '#cxc_filelist' ).html( '<img src="' +  response.image_url + '">' );
									jQuery( 'input[name="cxc_file_field"]' ).val( response.image_url );
								}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 ){

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

}
?>

Overall, using a custom upload field in WooCommerce checkout may be useful since it allows your customers to upload any necessary files throughout the checkout process.

Do you have any suggestions for further methods? Please let us know in the comments!

In WooCommerce, how can I upload a file field?

Navigate to the new field selections. Set the Allowed file types option under the Advanced tab. The list contains all of the formats that WordPress supports.

Also Read:

How to Reorder Checkout Fields In WooCommerce

Automatically Update Cart when quantity changed in WooCommerce

How to Edit Payment Gateway Title and Description in WooCommerce

How useful was this blog?

Click on a star to rate it!

Average rating 3.6 / 5. Vote count: 984

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

6 comments

  1. Thank you so much this is very helpful. but, I need a field that .png, .jpg, .jpeg, and .pdf and .doc can upload.
    If there is an article or any method for doing that please let me know.

Leave a comment

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