Well, I have a problem, I am wondering how I can create additional inputs above the "quantity of items" and "add to cart" sections so that the customer can personalize their product for themselves. I’d like to be able to do this myself in my theme without plugins unless any actually meet these goals.
I am wondering if a good choice is to use the ‘woocommerce_before_add_to_cart_button’ hookup? How do I later add the values of these inputs to this product to be able to display them in the order summary?
Currently I have this code that adds the field itself.
Unfortunately, these fields do not display either in the shopping cart, the order summary or the order in the ACP. What am I doing wrong? Is this the right way to go?
function my_personalization_field() {
$html = '<div class="personalization-field">';
$html .= '<label for="personalization">Personalization:</label>';
$html .= '<input type="text" id="personalization" name="my_personalization" />';
$html .= '</div>';
echo $html;
}
add_action('woocommerce_before_add_to_cart_button', 'my_personalization_field');
function my_adding_custom_data_in_order_items_meta( $item_id, $values, $cart_item_key ) {
if ( isset($values['my_personalization']) ) {
$custom_value = $values['my_personalization'];
wc_add_order_item_meta($item_id, 'my_personalization', $custom_value );
}
}
add_action('woocommerce_add_order_item_meta','my_adding_custom_data_in_order_items_meta', 10, 3 );
function my_display_personalization_data_in_cart($product_name, $cart_item, $cart_item_key) {
if(isset($cart_item['my_personalization'])) {
$product_name .= '<br><small>Personalization: ' . esc_html($cart_item['my_personalization']) . '</small>';
}
return $product_name;
}
add_filter('woocommerce_cart_item_name', 'my_display_personalization_data_in_cart', 10, 3);
2
Answers
You would need to add that data to the cart session and then you can access that on cart/checkout/order page.
Your code is a bit outdated and incomplete. Try use the following replacement code to display your custom field value in cart, checkout, orders and email notifications:
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.
You will get:
On cart and checkout pages:
On customer order pages:
On email notifications:
On admin orders pages: