When developing a WooCommerce theme, a common requirement is to allow users to add some custom information to a product when adding it to the cart (as shown in the image below) and then display this information on the cart page, checkout page, and backend order management page. For example, if we’re selling customized T-shirts, we need the user to fill in the customized text when adding to the cart and then follow this information through the order process. This article will detail how to achieve this requirement.
Step 1: Add Custom Input Fields
First, we need to add a custom information input field on the product detail page. We can use the woocommerce_before_add_to_cart_button hook to add the field before the “Add to Cart” button.
add_action('woocommerce_before_add_to_cart_button', function ()
{
echo '<div class="custom-field">
<label for="custom_data">Custom Information: </label>
<input type="text" id="custom_data" name="custom_data" value="">
</div>';
});
Step 2: Save Custom Data to Cart Items
When the user clicks the “Add to Cart” button, we need to get the user’s custom information and save it to the cart item. We can use the woocommerce_add_cart_item_data filter to achieve this.
add_filter('woocommerce_add_cart_item_data', function ($cart_item_data, $product_id, $variation_id)
{
if (isset($_POST[ 'custom_data' ])) {
$cart_item_data[ 'custom_data' ] = sanitize_text_field($_POST[ 'custom_data' ]);
}
return $cart_item_data;
}, 10, 3);
Step 3: Display Custom Data on the Cart and Checkout Pages
Now that the data is saved in the cart, we need to display it on the cart and checkout pages. We can use the woocommerce_get_item_data filter.
add_filter('woocommerce_get_item_data', function ($data, $cart_item)
{
if (isset($cart_item[ 'custom_data' ])) {
$data[] = [
'name' => 'Custom Information',
'value' => $cart_item[ 'custom_data' ],
];
}
return $data;
}, 10, 2);
Step 4: Save Custom Data to Order Items
When the user places an order, we need to save the custom data from the cart item to the order item so it can be viewed in the backend order management. We can use the woocommerce_checkout_create_order_line_item hook.
add_action('woocommerce_checkout_create_order_line_item', function ($item, $cart_item_key, $values, $order)
{
if (isset($values[ 'custom_data' ])) {
$item->add_meta_data('Custom Information', $values[ 'custom_data' ]);
}
}, 10, 4);
Conclusion
Through the steps above, we’ve implemented the feature of adding and displaying custom information during the WooCommerce product ordering process. This is very useful for personalized products or products requiring extra user input. You can modify the field types and data processing logic according to your actual needs.
