M
M
MissionDone2021-04-05 11:15:18
Delivery
MissionDone, 2021-04-05 11:15:18

How to display a box under Woocommerce shipping selection?

Please help with woocommerce.
When paying for an order, under the selected delivery point, you need to display a field where the client will indicate the time (in text).
This field should be sent to the mail with other order data.

add_action( 'woocommerce_after_shipping_rate', 'carrier_custom_fields', 20, 2 );
function carrier_custom_fields( $method, $index ) {
    if( ! is_checkout()) return; // Only on checkout page

    $customer_carrier_method = 'local_pickup:2';

    if( $method->id != $customer_carrier_method ) return; // Only display for "local_pickup"

    $chosen_method_id = WC()->session->chosen_shipping_methods[ $index ];

    // Если выбран метод доставки "самовывоз", показываем:
    if($chosen_method_id == $customer_carrier_method ):

    echo '<div class="custom-carrier">';

    woocommerce_form_field( 'carrier_name' , array(
        'type'          => 'text',
        'class'         => array('form-row-wide carrier-name'),
        'label'         => 'Время самовывоза:',
        'required'      => false,
    ), WC()->checkout->get_value( 'carrier_name' ));

    echo '</div>';
    endif;
}

// Валидация поля
add_action('woocommerce_checkout_process', 'carrier_checkout_process');
function carrier_checkout_process() {
    if( isset( $_POST['carrier_name'] ) && empty( $_POST['carrier_name'] ) )
        wc_add_notice( ( "Пожалуйста, введите время самовывоза" ), "error" );
}

add_action( 'woocommerce_checkout_update_order_meta', 'carrier_update_order_meta', 30, 1 );
function carrier_update_order_meta( $order_id ) {
    if( isset( $_POST['carrier_name'] ))
        update_post_meta( $order_id, '_carrier_name', sanitize_text_field( $_POST['carrier_name'] ) );
}


The field appears, but the page after sending the order gives an error.
Added keys, did not help either.

add_action( 'woocommerce_admin_order_data_after_shipping_address', 'custom_field_display_admin_order_meta', 10, 1 );

function custom_field_display_admin_order_meta($order){
    echo '<p><strong>'.__('Время самовывоза').':</strong> ' . get_post_meta( $order->id, '_carrier_name', true ) . '</p>';
}

// Выводим значения полей в шаблоне письма с заказом
add_filter('woocommerce_email_order_meta_keys', 'email_checkout_field_order_meta_keys');

function email_checkout_field_order_meta_keys( $keys ) {

$keys['Время самовывоза'] = '_carrier_name';

return $keys;
}


How can this error be fixed? The order is placed in the admin panel, but notifications are not received by mail

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question