我根据订单数量创建了一些额外的表单字段。因此,如果我在购物车中订购了2件商品,则该字段应该两次。
一切正常,……
以下是在订单中保存所有相关自定义结帐值的正确方法,并按照结算明细下面的编辑页面显示它们:
// Add checkout custom text fields add_action( 'woocommerce_before_order_notes', 'add_checkout_custom_text_fields', 20, 1 ); function add_checkout_custom_text_fields( $checkout) { $index = 0; // 1st Loop through cart items foreach(WC()->cart->get_cart() as $cart_item){ $index++; // 2nd Loop through each unit related to item quantity for($i = 1; $i <= $cart_item['quantity']; $i++){ woocommerce_form_field("my_field[$index][$i]", array( 'type' =>'text', 'class'=>array('my-field-class form-row-wide'), 'label'=>__('My Field')." (item $index - $i)", 'placeholder'=>__('Please enter your data'), ), $checkout->get_value("my_field[$index][$i]")); } } } // Save fields in order meta data add_action('woocommerce_checkout_create_order', 'save_custom_fields_to_order_meta_data', 20, 2 ); function save_custom_fields_to_order_meta_data( $order, $data ) { $index = 0; // 1st Loop through order items foreach( $order->get_items() as $item ){ $index++; // 2nd Loop through each unit related to item quantity for($i = 1; $i <= $item->get_quantity(); $i++){ if (isset( $_POST['my_field'][$index][$i]) && ! empty($_POST['my_field'][$index][$i]) ){ $order->update_meta_data( '_my_field_'.$index.'_'.$i, esc_attr( $_POST['my_field'][$index][$i] ) ); } } } } // Display fields in order edit pages add_action('woocommerce_admin_order_data_after_billing_address','display_custom_fields_in_admin_order', 20, 1); function display_custom_fields_in_admin_order( $order ){ $index = 0; // 1st Loop through order items foreach( $order->get_items() as $item ){ $index++; // 2nd Loop through each unit related to item quantity for($i = 1; $i <= $item->get_quantity(); $i++){ $my_field = get_post_meta($order->get_id(),'_my_field_'.$index.'_'.$i, true ); if (! empty($my_field) ){ echo '<p><strong>'.__('My Field')." <em>(item $index - $i)</em>".':</strong> ' . $my_field . '</p>'; } } } }
代码位于活动子主题(或活动主题)的function.php文件中。经过测试和工作