Получатель электронной почты на основе значения настраиваемого поля в WooCommerce

Я добавил настраиваемое поле на страницу оформления заказа в моем магазине Woocommerce. Поле - «Расположение ресторана». После того, как покупатель разместит заказ, моя цель - использовать поле «Местоположение ресторана», чтобы определить, на какой адрес электронной почты следует отправить подтверждение заказа.

Вот как я определил настраиваемое поле.

/////// Hook custom field in ///////

add_filter( 'woocommerce_checkout_fields', 'custom_checkout_fields' );

function custom_checkout_fields( $fields ) {

$fields['order']['restaurant_location'] = array(
'label'       => __('Food options', 'woocommerce'),
'placeholder' => _x('', 'placeholder', 'woocommerce'),
'required'    => true,
'clear'       => false,
'type'        => 'select',
'options'     => array(
    'no' => __('New Orleans', 'woocommerce' ),
    'br' => __('Baton Rouge', 'woocommerce' )
    )
);

 return $fields;

}

Вот моя попытка фильтра электронной почты.

add_filter( 'woocommerce_email_recipient_new_order', 'gon_conditional_email_recipient', 10, 2 );

function gon_conditional_email_recipient( $recipient, $order ) {

$gon_order_data = $order->get_data();
$gon_restaurant_location = $gon_order_data['order']['restaurant_location'];

if (  $gon_restaurant_location == 'New Orleans' ) {
    $recipient = '[email protected]';
    return $recipient;
} 
else if (  $gon_restaurant_location == 'Baton Rouge' ) {
    $recipient = '[email protected]';
    return $recipient;
} 

return $recipient;


}

Фильтр электронной почты работает, то есть я могу получить электронное письмо для перехода на любой адрес, но я не могу правильно вставить переменную '$gon_restaurant_location'. Любые идеи?

Спасибо,

pS


person peanutSquiggle    schedule 15.09.2017    source источник


Ответы (1)


Значение вашего настраиваемого поля не сохраняется в базе данных, поэтому не работает. Вместо этого попробуйте это полное решение:

// Add the custom checkout field
add_filter( 'woocommerce_after_order_notes', 'restaurant_location_checkout_field' );
function restaurant_location_checkout_field( $checkout ) {

    woocommerce_form_field( 'restaurant_location', array(
        'type'        => 'select',
        'class'       => array('my-field-class form-row-wide'),
        'label'       => __('Food options', 'woocommerce'),
        'required'    => true,
        'options'     => array(
            ''   => __('Please select an option', 'woocommerce' ),
            'New Orleans' => __('New Orleans', 'woocommerce' ),
            'Baton Rouge' => __('Baton Rouge', 'woocommerce' )
        )
    ), $checkout->get_value( 'restaurant_location' ));
}

// Process the checkout (checking)
add_action('woocommerce_checkout_process', 'restaurant_location_field_process');
function restaurant_location_field_process() {
    // Check if set, if its not set add an error.
    if ( ! $_POST['restaurant_location'] )
        wc_add_notice( __( 'Please select a food option .' ), 'error' );
}

// Update the order meta with field value
add_action( 'woocommerce_checkout_update_order_meta', 'restaurant_location_field_update_order_meta' );
function restaurant_location_field_update_order_meta( $order_id ) {
    if ( ! empty( $_POST['restaurant_location'] ) ) {
        update_post_meta( $order_id, '_restaurant_location', sanitize_text_field( $_POST['restaurant_location'] ) );
    }
}

// Display field value on the order edit page
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>'.__('Food options', 'woocommerce').':</strong> ' . get_post_meta( $order->get_id(), '_restaurant_location', true ) . '</p>';
}

// Conditional Email recipient filter based on restaurant location
add_filter( 'woocommerce_email_recipient_new_order', 'conditional_email_recipient', 10, 2 );
function conditional_email_recipient( $recipient, $order ) {
    if( is_admin() ) return $recipient;

    $location = get_post_meta( $order->get_id(), '_restaurant_location', true );
    $recipient = $location == 'New Orleans' ? ',[email protected]' : ',[email protected]';
    return $recipient;
}

Код находится в файле function.php вашей активной дочерней темы (или темы) или также в любом файле плагина.

Этот код протестирован на Woocommerce 3+ и работает


На основе официальной документации разработчика: Добавление настраиваемого специального поля

person LoicTheAztec    schedule 15.09.2017
comment
Я собирался спросить, сохраняет информацию где-нибудь OP. Хотя я бы предложил перейти на woocommerce_checkout_create_order для прямой совместимости с их методами CRUD. - person helgatheviking; 15.09.2017
comment
@helgatheviking хорошее предложение +1 ... Персоналу WooCommerce следует обновить документацию по своим полям оформления заказа ... Даже есть некоторые оставшиеся ошибки, такие как get_post_meta( $order->id на нем. - person LoicTheAztec; 15.09.2017