Сохраните пользовательские поля оформления заказа и отобразите их в заказах администратора Woocommerce


Я создал несколько дополнительных полей формы в соответствии с количеством заказов, которые у меня есть. Поэтому, если я заказываю 2 количества товаров в своей корзине, поле должно появиться дважды.

Все работает нормально, за исключением того, что я получаю ввод только для одного поля в форме заказа. Я хочу иметь отдельные значения для каждого аналогичного поля формы.

foreach(WC()->cart->get_cart() as $cart_item){
    //2nd Loop go through each unit related to item quantity
    for($i = 1; $i <= $cart_item['quantity']; $i++){
        $index++;

        woocommerce_form_field('myname', array(
            'type' =>'text',
            'class'=>array('my-field-class form-row-wide'),
            'label'=>__('My Name'),
            'placeholder'=>__('Please enter your name'),
        ), $checkout->get_value('myname'));

Я обновляю это:

add_action('woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta');
function my_custom_checkout_field_update_order_meta($order_id){
    if (! empty( $_POST['myname'])){
        update_post_meta($order_id,'Aspirant Name', sanitize_text_field($_POST['myname']));
    }
}

И отобразите с помощью этого:

add_action('woocommerce_admin_order_data_after_billing_address','my_custom_checkout_field_display_admin_order_meta', 10, 1);
function my_custom_checkout_field_display_admin_order_meta($order){
    echo '<p><strong>'.__('My Name').':</strong> ' . get_post_meta($order->get_id(),'My Name', true).'</p>';
}

Любая помощь приветствуется.

Author: LoicTheAztec, 2018-04-20

1 answers

Вот правильный способ сохранить все связанные пользовательские значения для оформления заказа в заказе и отобразить их на страницах редактирования заказа ниже сведений о выставлении счета:

// 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 файл вашей активной дочерней темы (или активной темы). Протестировано и работает

 1
Author: LoicTheAztec, 2018-04-19 23:34:20