I am trying to add a simple input field to the order backend and use it to update my order item information. It's a simple meta called "Number of People".
It seems like everything is working ok, except that saving the order does NOT update the meta field the way it's built right now. What could I be doing wrong?
/* Add custom field to cart item data */
add_filter('woocommerce_add_cart_item_data',
function ($cart_item_data, $product_id, $variation_id) {
if (isset($_POST['number_of_people'])) {
$cart_item_data['number_of_people'] = (int) sanitize_text_field($_POST['number_of_people']);
}
return $cart_item_data;
}, 10, 3);
/* Add custom field to order line item */
add_action('woocommerce_checkout_create_order_line_item',
function ($item, $cart_item_key, $values, $order) {
if (isset($values['number_of_people'])) {
$item->add_meta_data(__('Number of People', 'woocommerce'), $values['number_of_people']);
}
}, 10, 4);
add_action('woocommerce_admin_order_data_after_billing_address', 'print_custom_fields_in_the_admin_order', 10, 1);
function print_custom_fields_in_the_admin_order($order)
{
$order = wc_get_order($order->get_id());
foreach ($order->get_items() as $item_id => $item) {
if (has_term('group-class', 'product_cat', $item->get_product_id())) {
$number_of_people = $item->get_meta('Number of People', true);
error_log('Number of People: ' . $number_of_people);
break;
}
}
?>
<div class="billing-custom-fields">
<h4>Additional Information</h4>
<p><small>Click on the fields below to edit the values</small></p>
<div class="order-custom-fields">
<label for="_number_of_people">Number of People:</label>
<input type="number" id="_number_of_people" name="_number_of_people"
value="<?php echo esc_attr($number_of_people); ?>" />
</div>
</div>
<?php
}
/** Save custom fields when order is updated in admin */
add_action('woocommerce_process_shop_order_meta', 'update_custom_fields_in_the_admin_order');
function update_custom_fields_in_the_admin_order($order_id)
{
if (! isset($_POST['_number_of_people'])) {
return;
}
$meta_value = sanitize_text_field($_POST['_number_of_people']);
$order = wc_get_order($order_id);
foreach ($order->get_items() as $item_id => $item) {
if (has_term('group-class', 'product_cat', $item->get_product_id())) {
$item->update_meta_data('Number of People', $meta_value);
$item->save();
break;
}
}
$order->calculate_totals();
}
I have tried cleaning cache, even through PHP. I have tried different orders. I have tried different items.
Can't see real problems on the code. Very probably missing something
nameis_number_of_peopleand your code is looking fornumber_of_people, eg.$_POST['number_of_people']inwoocommerce_add_cart_item_data.