Отображение пользовательских полей заказа на странице заказа WooCommerce и электронных письмах - PullRequest
1 голос
/ 03 мая 2019

У меня есть настраиваемые поля оформления заказа в зависимости от количества товаров в корзине. Теперь мне нужно отобразить метаданные сохраненного заказа на странице Заказа и уведомления по электронной почте.

Это код для полей: Добавление пользовательских полей на основе количества корзин

add_action( 'woocommerce_before_checkout_billing_form', 'srd_custom_einstiegswahl');
function srd_custom_einstiegswahl( $checkout ){

    $count = 1;

    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {
        $options       = array( '' => __("Bitte wählen Sie Ihren Einstiegsort") ); 
        $einstiegsorte = get_post_meta( $cart_item[ 'product_id' ], '_einstiegsorte', true );

        if( ! empty($einstiegsorte) ){
            $option_items = explode( "\n", $einstiegsorte );
            if( sizeof( $option_items ) > 1 ){
                foreach( $option_items as $value )
                    $options[$value] = $value;
            } else {
                $value = str_replace('\n', '', $einstiegsorte);
                $options[$value] = $value;
            }
        }

        // Loop through cart item quantity
        for($i = 1; $i <= $cart_item['quantity']; $i++ ) {

            $j = $count.'_'.$i;

            echo '<h6>Reiseteilnehmer '.$i . '</h6>';

            woocommerce_form_field( '_teilnehmer_vorame_'.$j, array(
                    'type'          => 'text',
                     'class'         => array('checkout_vorname'),
                    'label'         => __('Vorame'),
                    'required'      => true,
            ), $checkout->get_value( '_teilnehmer_vorame_'.$j ));

            woocommerce_form_field( '_teilnehmer_nachname_'.$j, array(
                    'type'          => 'text',
                    'class'         => array('checkout_nachname'),
                    'label'         => __('Nachname'),
                    'required'      => true,
            ), $checkout->get_value( '_teilnehmer_nachname_'.$j ));

            woocommerce_form_field( '_teilnehmer_einstiegswahl_'.$j, array(
                'type'          => 'select',
                'class'         => array('checkout_einstiegswahl'),
                'label'         => __('Einstiegswahl'),
                'required'      => true,
                'options'       => $options,
            ), $checkout->get_value( '_teilnehmer_einstiegswahl_'.$j ));
        }
        $count++;
    }
}

Обновление метаданных заказа со значениями настраиваемых полей оформления заказа

add_action('woocommerce_checkout_create_order', 'srd_teilnehmer_checkout_create_order', 20, 2 );
function srd_teilnehmer_checkout_create_order( $order, $data ) {
    $count = 1;

    // Loop through cart item quantity
    foreach( WC()->cart->get_cart() as $cart_item ) {

        // Loop through item quantity
        for($i = 1; $i <= $cart_item['quantity']; $i++ ) {

            $j = $count.'_'.$i;

            if ( isset($_POST['_teilnehmer_vorame_'.$j]) )
                $order->update_meta_data( '_teilnehmer_vorame_'.$j , sanitize_text_field($_POST['_teilnehmer_vorame_'.$j]) );

            if ( isset($_POST['_teilnehmer_nachname_'.$j]) )
                $order->update_meta_data( '_teilnehmer_nachname_'.$j, sanitize_text_field($_POST['_teilnehmer_nachname_'.$j]) );

            if ( isset($_POST['_teilnehmer_einstiegswahl_'.$j]) )
                $order->update_meta_data( '_teilnehmer_einstiegswahl_'.$j, sanitize_text_field($_POST['_teilnehmer_einstiegswahl_'.$j]) );
        }
        $count++;
    }
}

Это моя попытка отобразить сохраненные поля:

function srdreiseteilnehmer($order_id) {

    $count = 1;

    $key_labels = array( 'vorame', 'nachname', 'einstiegswahl' );

    // Loop through order items
    foreach ( $order_id->get_items() as $item ){



        // Loop through item quantity
        for($i = 1; $i <= $item->get_quantity(); $i++ ) {

            echo '<tbody>';



            // Loop through attendee fields
            foreach( $key_labels as $key ){
                $value = get_post_meta( $order_id, '_teilnehmer_'.$key.'_'.$count.'_'.$i, true );
                echo '<tr><th>'.ucfirst($key).':</th><td>'.$value.'</td></tr>';
            }

            echo '</tbody>';
        }
        $count++;
    }
}

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

Любая помощь будет принята с благодарностью.

1 Ответ

0 голосов
/ 04 мая 2019

Я повторно посетил ваш код (который, кажется, основан на одном из моих предыдущих ответов) .

Я добавил недостающее подтверждение поля для страницы оформления заказа, отображая данные участников на странице Заказа (спасибо) и в уведомлениях по электронной почте:

// Participant fields labels names
function teilnehmer_fields_labels(){
    $domain = 'woocommerce';
    return [
        __('Vorame', $domain),
        __('Nachname', $domain),
        __('Einstiegswahl', $domain)
    ];
}

// Checkout custom fields display
add_action( 'woocommerce_before_checkout_billing_form', 'srd_custom_einstiegswahl');
function srd_custom_einstiegswahl( $checkout ){
    $teilnehmer_labels = teilnehmer_fields_labels();
    $count = 1;

    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {

        // Loop through cart item quantity
        for($i = 1; $i <= $cart_item['quantity']; $i++ ) {
            echo '<h6>Reiseteilnehmer '.$i . '</h6>';

            // Loop through participants keys / labels pairs
            foreach( $teilnehmer_labels as $label ){
                $key = strtolower($label);
                $field_key = '_teilnehmer_'.$key.'_'.$count.'_'.$i;

                woocommerce_form_field( $field_key, array(
                        'type'          => 'text',
                         'class'         => array('form-row-wide checkout_'.$key),
                        'label'         => $label,
                        'required'      => true,
                ), '' );
            }
        }
        $count++;
    }
}

// Checkout custom fields save to order meta
add_action('woocommerce_checkout_create_order', 'srd_teilnehmer_checkout_create_order', 10, 2 );
function srd_teilnehmer_checkout_create_order( $order, $data ) {
    $teilnehmer_labels = teilnehmer_fields_labels();
    $count = 1;

    // Loop through cart item quantity
    foreach( $order->get_items() as $item ) {

        // Loop through item quantity
        for($i = 1; $i <= $item->get_quantity(); $i++ ) {

            // Loop through participants keys / labels pairs
            foreach( $teilnehmer_labels as $label ) {
                $field_key = '_teilnehmer_'.strtolower($label).'_'.$count.'_'.$i;

                if ( isset($_POST[$field_key]) ) {
                    $order->update_meta_data( $field_key , sanitize_text_field($_POST[$field_key]) );
                }
            }
        }
        $count++;
    }
}

// Checkout custom fields validation
add_action('woocommerce_checkout_process', 'srd_teilnehmer_checkout_process' );
function srd_teilnehmer_checkout_process() {
    $teilnehmer_labels = teilnehmer_fields_labels();
    $count = 1;
    $error = false;

    // Loop through cart item quantity
    foreach( WC()->cart->get_cart() as $cart_item ) {

        // Loop through item quantity
        for($i = 1; $i <= $cart_item['quantity']; $i++ ) {

            // Loop through participants keys / labels pairs
            foreach( $teilnehmer_labels as $label ) {
                $field_key = '_teilnehmer_'.strtolower($label).'_'.$count.'_'.$i;

                if ( isset($_POST[$field_key]) && empty($_POST[$field_key]) ) {
                    $error = true;
                }
            }
        }
        $count++;
    }

    if ( $error ) {
        wc_add_notice( __( 'Please fill in all participants fields' ), 'error' );
    }
}

// Display order custom meta data in Order received (thankyou) page
add_action('woocommerce_thankyou', 'srd_teilnehmer_thankyou', 10, 2 );
function srd_teilnehmer_thankyou( $order_id ) {
    $teilnehmer_labels = teilnehmer_fields_labels();
    $order = wc_get_order( $order_id );
    $count = 1;

    // Loop through order items
    foreach ( $order->get_items() as $item ){

        // Loop through item quantity
        for($i = 1; $i <= $item->get_quantity(); $i++ ) {
            echo '<h6>Reiseteilnehmer '.$i . '</h6>';
            echo '<table><tbody>';

            // Loop through participants keys / labels pairs
            foreach( $teilnehmer_labels as $label ){
                $meta_key = '_teilnehmer_'.strtolower($label).'_'.$count.'_'.$i;

                echo '<tr><th>'.$label.':</th><td>'.$order->get_meta( $meta_key ).'</td></tr>';
            }

            echo '</tbody></table>';
        }
        $count++;
    }
}

// Display order custom meta data on email notifications
add_action('woocommerce_email_order_details', 'action_after_email_order_details', 25, 4 );
function action_after_email_order_details( $order, $sent_to_admin, $plain_text, $email ) {
    $teilnehmer_labels = teilnehmer_fields_labels();
    $count = 1;

    // The HTML Structure
    $html_output = '<h2>' . __( 'Teilnehmer', 'woocommerce' ) . '</h2>
    <div class="teilnehmer-info">
        <table cellspacing="0" cellpadding="6"><tbody>';

    // Loop through order items
    foreach ( $order->get_items() as $item ){

        // Loop through item quantity
        for($i = 1; $i <= $item->get_quantity(); $i++ ) {
            $html_output .= '<tr class="subtitle"><td colspan="2"><h3>' . __("Reiseteilnehmer", "woocommerce") . $i . '</h3></td></tr>';


            // Loop through participants keys / labels pairs
            foreach( $teilnehmer_labels as $label ){
                $meta_key = '_teilnehmer_'.strtolower($label).'_'.$count.'_'.$i;

                $html_output .= '<tr><th>'.$label.':</th><td>'.$order->get_meta( $meta_key ).'</td></tr>';
            }
        }
        $count++;
    }

    $html_output .= '</tbody></table>
    </div><br>'; // HTML (end)

    // The CSS styling
    $styles = '<style>
        .teilnehmer-info table{width: 100%; font-family: \'Helvetica Neue\', Helvetica, Roboto, Arial, sans-serif;
            color: #737373; border: 1px solid #e4e4e4; margin-bottom:8px;}
        .teilnehmer-info table th, table.teilnehmer-info td{text-align: left; border-top-width: 4px;
            color: #737373; border: 1px solid #e4e4e4; padding: 12px;}
        .teilnehmer-info table td{text-align: left; border-top-width: 4px; color: #737373; border: 1px solid #e4e4e4; padding: 12px;}
        .teilnehmer-info table tr.subtitle h3{margin: 0;}
    </style>';

    // The Output CSS + HTML
    echo $styles . $html_output;
}

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

В конце страницы Заказа получено:

enter image description here

В уведомлениях по электронной почте:

enter image description here

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