How to add File Upload in WooCommerce Checkout Page
Use Case Scenario:
A WooCommerce Store wants to have a file upload functionality within the Checkout Page. The file upload would enable customers to upload a document when they checkout.
This WooCommerce tutorial will add a file upload functionality in WooCommerce Checkout Page without using a plugin.
NOTE: This is using the WooCommerce Classic Checkout Page. If your using the WooCommerce Block Checkout page, change it to the Classic Checkout page to use this code
Copy the code below and paste it inside your functions.php file
add_action( ‘woocommerce_after_order_notes’, ‘wehelpcode_checkout_file_upload’ );
function wehelpcode_checkout_file_upload() {
echo ‘Application Form (PDF)*’;
wc_enqueue_js( “
$( ‘#appform’ ).change( function() {
if ( this.files.length ) {
const file = this.files[0];
const formData = new FormData();
formData.append( ‘appform’, file );
$.ajax({
url: wc_checkout_params.ajax_url + ‘?action=appformupload’,
type: ‘POST’,
data: formData,
contentType: false,
enctype: ‘multipart/form-data’,
processData: false,
success: function ( response ) {
$( ‘input[name=”appform_field”]’ ).val( response );
}
});
}
});
” );
}
add_action( ‘wp_ajax_appformupload’, ‘wehelpcode_appformupload’ );
add_action( ‘wp_ajax_nopriv_appformupload’, ‘wehelpcode_appformupload’ );
function wehelpcode_appformupload() {
global $wpdb;
$uploads_dir = wp_upload_dir();
if ( isset( $_FILES[‘appform’] ) ) {
if ( $upload = wp_upload_bits( $_FILES[‘appform’][‘name’],
null, file_get_contents( $_FILES[‘appform’][‘tmp_name’] ) ) )
{
echo $upload[‘url’];
}
}
die;
}
add_action( ‘woocommerce_checkout_process’, ‘wehelpcode_validate_new_checkout_field’ );
function wehelpcode_validate_new_checkout_field() {
if ( empty( $_POST[‘appform_field’] ) ) {
wc_add_notice( ‘Please upload your Application Form’, ‘error’ );
}
}
add_action( ‘woocommerce_checkout_update_order_meta’, ‘wehelpcode_save_new_checkout_field’ );
function wehelpcode_save_new_checkout_field( $order_id ) {
if ( ! empty( $_POST[‘appform_field’] ) ) {
update_post_meta( $order_id, ‘_application’, $_POST[‘appform_field’] );
}
}
add_action( ‘woocommerce_admin_order_data_after_billing_address’,
‘wehelpcode_show_new_checkout_field_order’, 10, 1 );
function wehelpcode_show_new_checkout_field_order( $order ) {
$order_id = $order->get_id();
if ( get_post_meta( $order_id, ‘_application’, true ) )
echo ‘Purchase Order: ‘ . get_post_meta( $order_id, ‘_application’, true ) . ”;
}
add_action( ‘woocommerce_email_after_order_table’, ‘wehelpcode_show_new_checkout_field_emails’, 20, 4 );
function wehelpcode_show_new_checkout_field_emails( $order, $sent_to_admin, $plain_text, $email ) {
if ( $sent_to_admin && get_post_meta( $order->get_id(), ‘_application’, true ) )
echo ‘Purchase Order: ‘ . get_post_meta( order->get_id(), ‘_application’, true ) . ”;
}