How to Add a File Upload Field to the WooCommerce Checkout Page

During WooCommerce customization, we often encounter the need for users to upload files on the checkout page. To implement this functionality, we need to add a custom file upload field to the checkout form. While it might seem like a simple field addition, the underlying implementation requires a fair amount of work. Let’s explore the detailed code required.

1. Adding a File Upload Field and Using Ajax for Uploads

Add the File Upload Form

First, we need to add a hidden field and a file input field to the checkout page. The hidden field will store the URL of the uploaded file once the upload is complete.

add_action( 'woocommerce_after_checkout_billing_form', 'misha_upload_field' );

function misha_upload_field() {

        // Here we add a hidden field to store the uploaded file URL
        woocommerce_form_field( 'misha_file_field', array(
                'type' => 'hidden',
        ) );

        // Here is our file upload field and a container for the preview
        echo '<div id="misha_filelist"></div>
        <input type="file" id="misha_file" name="misha_file">';

}

Implement the Upload Functionality Using Ajax

Next, we use JavaScript to handle the file upload via Ajax. This allows the file to be uploaded to the server as soon as the user selects it, without needing to submit the entire checkout form first.

jQuery( function( $ ) {

        $( '#misha_file' ).change( function() {

                if ( ! this.files.length ) {
                        $( '#misha_filelist' ).empty();
                } else {

                        // we need only the only one for now, right?
                        const file = this.files[0];

                        $( '#misha_filelist' ).html( '<img src="' + URL.createObjectURL( file ) + '"><span>' + file.name + '</span>' );

                        const formData = new FormData();
                        formData.append( 'misha_file', file );

                        $.ajax({
                                url: wc_checkout_params.ajax_url + '?action=mishaupload',
                                type: 'POST',
                                data: formData,
                                contentType: false,
                                enctype: 'multipart/form-data',
                                processData: false,
                                success: function ( response ) {
                                        $( 'input[name="misha_file_field"]' ).val( response );
                                }
                        });

                }

        } );

} );

2. Receiving and Saving Files on the Server via Ajax

Save the Uploaded Image to the Server

After the frontend initiates the Ajax upload, we need to handle the file on the backend. Below is an example of how to process and save the uploaded file. After saving, the server returns the file URL to the frontend. If further processing is required (like generating an attachment ID), you can also return the attachment ID; related code can be found in other articles on this site.

add_action( 'wp_ajax_mishaupload', 'misha_file_upload' );
add_action( 'wp_ajax_nopriv_mishaupload', 'misha_file_upload' );

function misha_file_upload(){

        $upload_dir = wp_upload_dir();

        if ( isset( $_FILES[ 'misha_file' ] ) ) {
                $path = $upload_dir[ 'path' ] . '/' . basename( $_FILES[ 'misha_file' ][ 'name' ] );

                if( move_uploaded_file( $_FILES[ 'misha_file' ][ 'tmp_name' ], $path ) ) {
                        echo $upload_dir[ 'url' ] . '/' . basename( $_FILES[ 'misha_file' ][ 'name' ] );
                }
        }
        die;
}

We have now completed the upload form and the step for saving the file. The final step is to associate this file with the WooCommerce order.

3. Saving the File URL to the Order and Displaying it

Save the File URL in Order Metadata

This part is relatively simple: we save the file URL submitted from the checkout form directly into the order’s metadata.

add_action( 'woocommerce_checkout_update_order_meta', 'misha_save_what_we_added' );

function misha_save_what_we_added( $order_id ){

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

}

Display Uploaded Images in the Admin Panel

To help administrators process the order, we should display the uploaded image directly on the order details page in the backend.

add_action( 'woocommerce_admin_order_data_after_order_details', 'misha_order_meta_general' );

function misha_order_meta_general( $order ){

        $file = get_post_meta( $order->get_id(), 'misha_file_field', true );
        if( $file ) {
                echo '<img src="' . esc_url( $file ) . '" />';
        }

}

Summary

While plugins like “Checkout Field Editor” can achieve similar results, specific features like file uploads often require a premium version. Implementing this via code is not only free but also offers greater flexibility, better performance, and full control over the integration. Developers requiring this functionality can use the code snippets above as a robust starting point.

Related Posts

Leave a Reply

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