Переопределить получателя из настраиваемого поля в почтовых уведомлениях клиентов Woocommerce - PullRequest
0 голосов
/ 15 ноября 2018

Имея дело с цифровыми продуктами, я добавил функцию GIFT, которая работает нормально, но она не работает, если пользовательское поле GIFT не заполнено. Если поле GIFT заполнено и когда для заказа установлено значение Complete, электронное письмо с полным заказом отправляется на адрес электронной почты, указанный в поле «ПОДАРОК», вместо того, который был введен в качестве электронного письма для выставления счета.

Есть идеи, где я здесь не так? Мне нужно отправить его на адрес электронной почты для выставления счета, если поле GIFT не заполнено, и если поле GIFT заполнено, отправлять только на адрес электронной почты, указанный в поле GIFT.

Вот код:

// add gift message on checkout
add_action( 'woocommerce_after_order_notes', 'custom_checkout_field_before_billing' );
function custom_checkout_field_before_billing() {
    $domain = 'woocommerce';

    ?>
    <style>p#gift_field{display:none;}</style>
    <div id="message">
    <h3><i class="fa fa-gift"></i><?php _e( ' Is this a gift?', 'woocommerce' ); ?></h3>
    <?php

    woocommerce_form_field( 'gift_msg', array(
        'type'  => 'checkbox',
        'class' => array( 'gift-checkbox' ),
        'label' => __( 'To whom is this a gift?', 'woocommerce' ),
    ), WC()->checkout->get_value( 'cb_msg' ));

    woocommerce_form_field( 'gift', array(
        'type'              => 'text',
        'class'             => array('msg t_msg'),
        'label'             => __('Enter the recipient\'s e-mail address, e.g: john.smith@email.com '),
        'placeholder'       => __(''),
    ), WC()->checkout->get_value( 'gift' ));

    echo '</div>';

    ?><script>
    jQuery(document).ready(function($) {
        var a = '#gift_field';
        $('input#gift_msg').change( function(){
            if( $(this).is(':checked') )
                $(a).show();
            else
                $(a).hide();
        });
    });
    </script><?php
}

// add validation if box is checked but field is not filled in
add_action('woocommerce_after_checkout_validation', 'is_this_a_gift_validation', 20, 2 );
function is_this_a_gift_validation( $data, $errors ) {

    if( isset($_POST['gift_msg']) && empty($_POST['gift']) )
        $errors->add( 'gift', __( "You've chosen to send this as a gift, but did not submit a recipient email address.", "woocommerce" ) );
}



// update the gift field meta
add_action( 'woocommerce_checkout_update_order_meta', 'is_this_a_gift_save_meta');
function is_this_a_gift_save_meta( $order_id ) {
    $gift_recipient_address = $_POST['gift'];
    if ( ! empty( $gift_recipient_address ) )
        update_post_meta( $order_id, 'gift', sanitize_text_field( $gift_recipient_address ) );
}


// add gift message to order page
function is_this_a_gift_order_display( $order ) {  ?>
    <div class="order_data_column">
        <h3><?php _e( '<br>Gift For:', 'woocommerce' ); ?></h3>
        <?php 
        echo get_post_meta( $order->id, 'gift', true ); ?>
    </div>
<?php }
add_action( 'woocommerce_admin_order_data_after_order_details', 'is_this_a_gift_order_display' );

Вот код, который не работает так, как мне нужно:

add_filter( 'woocommerce_email_recipient_customer_completed_order', 'is_this_a_gift_replace_email_recipient', 10, 2 );
function is_this_a_gift_replace_email_recipient( $recipient, $order ) {
    if ( ! is_a( $order, 'WC_Order' ) &&  ( ! empty( $gift_recipient_address ))) return $recipient;

    $recipient = get_post_meta( $order->id, 'gift', true );
    return $recipient;
}

Буду признателен за помощь. Заранее спасибо!

1 Ответ

0 голосов
/ 15 ноября 2018

В ваших двух последних функциях есть ошибки ... попробуйте следующее (которое заменит две последние функции) :

// add gift message to order page
add_action( 'woocommerce_admin_order_data_after_order_details', 'is_this_a_gift_order_display' );
function is_this_a_gift_order_display( $order ) {  

    if( $value = $order->get_meta('gift') ) :
        echo '<div class="order_data_column">
        <h3>' . __( '<br>Gift For:', 'woocommerce' ) . '</h3>
        <p>' . $value . '</p>
        </div>';
    endif;
}

add_filter( 'woocommerce_email_recipient_customer_completed_order', 'is_this_a_gift_replace_email_recipient', 10, 2 );
function is_this_a_gift_replace_email_recipient( $recipient, $order ) {
    $gift_recipient = $order->get_meta('gift');
    if ( is_a( $order, 'WC_Order' ) && $order->get_meta('gift') ) 
        $recipient = $order->get_meta('gift');

    return $recipient;
}

Код помещается в файл function.php вашей активной дочерней темы (active theme). Это должно работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...