Custom Product Text Field for WooCommerce

Adds a custom text field on WooCommerce product pages, saves user input, and displays it in the cart, checkout, and order details.

PHP
/**
 * Snippet Name:     Custom Product Text Field for WooCommerce
 * Snippet Author:   coding-bunny.com
 * Description:      Adds a custom text field on WooCommerce product pages, saves user input, and displays it in the cart, checkout, and order details.
 */

/**
 * Adds a custom text input field on the WooCommerce product page.
 */
add_action( 'woocommerce_before_add_to_cart_button', 'cb_custom_product_text_field' );
function cb_custom_product_text_field() {
    global $product;
    echo '<div class="cb_custom_product_text_field">
            <label for="custom-text">Personalize Product</label><br>
            <input type="text" id="custom-text" name="custom-text" placeholder="Enter your custom text here">
          </div>';
}

/**
 * Saves the custom text input in the cart item data.
 */
add_filter( 'woocommerce_add_cart_item_data', 'cb_save_custom_text_to_cart_data', 10, 3 );
function cb_save_custom_text_to_cart_data( $cart_item_data, $product_id, $variation_id ) {
    if ( !empty( $_POST['custom-text'] ) ) {
        $cart_item_data['custom-text'] = sanitize_text_field( $_POST['custom-text'] );
    }
    return $cart_item_data;
}

/**
 * Displays the custom text input in the cart, checkout, and order review pages.
 */
add_filter( 'woocommerce_get_item_data', 'cb_show_custom_field_data_under_product_name', 10, 2 );
function cb_show_custom_field_data_under_product_name( $item_data, $cart_item ) {
    if ( !empty( $cart_item['custom-text'] ) ) {
        $item_data[] = array(
            'key'     => __('Custom Text', 'woocommerce'),
            'value'   => esc_html( $cart_item['custom-text'] ),
        );
    }
    return $item_data;
}

/**
 * Saves the custom text input as order meta data, so it appears in the order details.
 */
add_action( 'woocommerce_checkout_create_order_line_item', 'cb_add_custom_field_data_as_order_meta', 10, 4 );
function cb_add_custom_field_data_as_order_meta( $item, $cart_item_key, $values, $order ) {
    if ( !empty( $values['custom-text'] ) ) {
        $item->add_meta_data( __('Custom Text:', 'woocommerce'), esc_html( $values['custom-text'] ) );
    }
}

How To Implement This Solution?

Leave a Reply

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

My Agile Privacy
This site uses technical and profiling cookies. You can accept, decline or customize cookies by pressing the desired buttons. By closing this policy you will continue without accepting.

Need help?

Choose one of the following options:

Powered by CodingBunny