Отображение значения настраиваемого поля оформления заказа в счете-фактуре Woocommerce pdf

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

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

  • находится в корзине, отобразить первое сообщение: (shipping_instructions_delivery_field_update_order_meta)
  • в противном случае отобразите сообщение два (shipping_instructions_pickup_field_update_order_meta).

Мой код:

// adds order note at checkout page for the RRNC to pickup at home
add_action( 'woocommerce_before_checkout_form', 'specific_checkout_content', 12 );
function specific_checkout_content() {
    // set your special category name, slug or ID here:
    $special_cat = 'randwick-rugby-netball-club';
    $bool = false;
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $item = $cart_item['data'];
        if ( has_term( $special_cat, 'product_cat', $item->id ) )
            $bool = true;
    }
    // If the special category is detected in one items of the cart
    // It displays the message
    if ($bool)
    {
      echo '<div class = "checkout-instructions"><p><strong>PLEASE PICK UP ORDER FROM THE CLUB.</strong></p></div>';
      add_filter( 'woocommerce_cart_needs_shipping_address', '__return_false');     //Removes the ship to different address for club store items
      add_filter( 'woocommerce_enable_order_notes_field', 'remove_wc_order_notes' );    //Removes the order notes
      add_action( 'woocommerce_checkout_update_order_meta', 'shipping_instructions_pickup_field_update_order_meta' );   //Adds the pick up note for the pdf slip
      add_action( 'woocommerce_checkout_process', 'my_custom_checkout_field_process_pickup' );
    }
  else
  {
     echo '<p><strong>Orders are dispatched within 2 business days and shipping times are estimated at between 3-7 business days depending on your location within Australia.</strong></p>';
    add_action( 'woocommerce_before_order_notes', 'delivery_instructions_field', 10 );  //Adds the Delivery Instructions fields to the checkout
    add_action( 'woocommerce_checkout_update_order_meta', 'shipping_instructions_delivery_field_update_order_meta' );   //Adds the delivery note for the pdf slip
    add_action( 'woocommerce_checkout_process', 'my_custom_checkout_field_process_delivery' );
  }
}

function my_custom_checkout_field_process_delivery( ) {
                global $woocommerce;
                // Check if set, if its not set add an error.
                if ( !$_POST[ 'delivery_instructions' ] )
                                wc_add_notice( __( 'Please select from the delivery options.' ), 'error' );
                                 /*$woocommerce->add_error( __( 'Please select from the delivery options.' ) );*/
                if ( !$_POST[ 'sport_instructions' ] )
                                wc_add_notice( __( 'Please select the sport of the order' ), 'error' );
                                /*$woocommerce->add_error( __( 'Please select the sport of the order' ) );*/
}

function my_custom_checkout_field_process_pickup( ) {
                global $woocommerce;
                // Check if set, if its not set add an error.
                if ( !$_POST[ 'sport_instructions' ] )
                                wc_add_notice( __( 'Please select the sport of the order' ), 'error' );
                                /*$woocommerce->add_error( __( 'Please select the sport of the order' ) );*/
}

// remove Order Notes from checkout field in Woocommerce
function remove_wc_order_notes() {
    return false;
}


function shipping_instructions_delivery_field_update_order_meta( $order_id ) {
            update_post_meta( $order_id, 'shipping_instructions', 'IF YOU HAVE NOT RECEIVED YOUR ORDER WITHIN 7 DAYS, PLEASE CONTACT US TO FOLLOW UP' );
}

function shipping_instructions_pickup_field_update_order_meta( $order_id ) {
            update_post_meta( $order_id, 'shipping_instructions', 'PLEASE PICK UP FROM THE CLUB SHOP' );
}

//Admin side
/**
 * Update the order meta with field value
 **/
add_action( 'woocommerce_checkout_update_order_meta', 'delivery_instructions_field_update_order_meta' );
function delivery_instructions_field_update_order_meta( $order_id ) {
                if ( $_POST[ 'delivery_instructions' ] )
                                update_post_meta( $order_id, 'delivery_instructions', esc_attr( $_POST[ 'delivery_instructions' ] ) );
}

add_action('woocommerce_admin_order_data_after_billing_address', 'my_custom_shipping_fields_display_admin_order_meta', 10, 1);

function my_custom_shipping_fields_display_admin_order_meta($order) {
echo '<p><strong>' . __('Shipping Note') . ':</strong><br> ' . get_post_meta($order->id, 'shipping_instructions', true) . '</p>';
}

$shipping_instructions = get_post_meta($wpo_wcpdf->export->order->id,'shipping_instructions',true);
if (isset($shipping_instructions)) {
    echo $shipping_instructions;
    }


/**
 * Add the delivery instructions field to the checkout
 **/

function delivery_instructions_field( $checkout ) {
                 echo '<div id = "delivery_instructions_field"><h2>' . __('Delivery Instructions') . '</h2>';
                woocommerce_form_field_radio( 'delivery_instructions', array(
                                 'type' => 'select',
                                'class' => array(
                                                 'delivery_instructions form-row-wide'
                                ),
                                'label' => __( '' ),
                                'placeholder' => __( '' ),
                                'required' => true,
                                'options' => array(
                                  'Signature Required' => '<b> Signature Required</b><br/>A signature is required for the goods to be left at the intended address. If there is no one to sign for your delivery, a card will be left and it is then your responsibility to collect the items from the nearest depot or arrange for the courier to return. This will be at your expense<br/><br/>',
                                  'Leave Unattended' => '<b> Authority to leave unattended</b><br/>Courier will leave your goods at the intended address. You can give directions in the “Order Notes” below for the best place to leave your delivery',

                                )
                ), $checkout->get_value( 'delivery_instructions' ) );
                echo '</div>';
}


add_action('woocommerce_admin_order_data_after_billing_address', 'my_custom_billing_fields_display_admin_order_meta', 10, 1);

function my_custom_billing_fields_display_admin_order_meta($order) {
echo '<p><strong>' . __('Delivery Instructions') . ':</strong><br> ' . get_post_meta($order->id, 'delivery_instructions', true) . '</p>';
}

$delivery_instructions = get_post_meta($wpo_wcpdf->export->order->id,'_delivery_instructions',true);
if (isset($delivery_instructions)) {
    echo $delivery_instructions;
    }

/**
 * Add the field to the checkout to get the sport of what the customer orders
 **/
add_action( 'woocommerce_after_order_notes', 'sport_instructions_field', 20 );
function sport_instructions_field( $checkout ) {
                 echo '<div id = "sport_instructions_field"><h2>' . __('Which sport is this order in relation to?') . '</h2>';
                woocommerce_form_field_radio( 'sport_instructions', array(
                                 'type' => 'select',
                                'class' => array(
                                                 'sport_instructions form-row-wide'
                                ),
                                'label' => __( '' ),
                                'placeholder' => __( '' ),
                                'required' => true,
                                'options' => array(
                                  'Rugby Union' => '<b>Rugby Union</b><br/>',
                                  'Rugby League' => '<b>Rugby League</b><br/>',
                                   'Netball' => '<b>Netball</b><br/>',
                                   'Football' => '<b>Football</b><br/>',
                                   'AFL' => '<b>AFL</b><br/>',
                                   'Touch Tag' => '<b>Touch & Tag</b>',

                                )
                ), $checkout->get_value( 'sport_instructions' ) );
                echo '</div>';
}

/**
 * Update the order meta with field value
 **/
add_action( 'woocommerce_checkout_update_order_meta', 'sport_instructions_field_update_order_meta' );
function sport_instructions_field_update_order_meta( $order_id ) {
                if ( $_POST[ 'sport_instructions' ] )
                                update_post_meta( $order_id, 'sport_instructions', esc_attr( $_POST[ 'sport_instructions' ] ) );
}

add_action('woocommerce_admin_order_data_after_billing_address', 'my_custom_sports_fields_display_admin_order_meta', 20, 1);

function my_custom_sports_fields_display_admin_order_meta($order) {
echo '<p><strong>' . __('Sport in relation to') . ':</strong><br> ' . get_post_meta($order->id, 'sport_instructions', true) . '</p>';
}

$sport_instructions = get_post_meta($wpo_wcpdf->export->order->id,'_sport_instructions',true);
if (isset($sport_instructions)) {
    echo $sport_instructions;
}

Я бы подумал, что update_post_meta() со строкой в ​​конце должен его установить, но он, похоже, ничего не делает. Или, возможно, у меня нет должной функциональности с:
function my_custom_checkout_field($checkout).

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

Вам лучше добавить весь связанный с вами код (даже код, который отображает ваши настраиваемые поля оформления заказа), поскольку без него невозможно решить вашу проблему.

LoicTheAztec 13.03.2018 09:47

Хорошо, я обновил код, чтобы показать все остальные работающие функции. Пробовал еще несколько вещей, но все равно не повезло.

8r3nd4n 19.03.2018 01:20
Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Symfony Station Communiqué - 7 июля 2023 г
Symfony Station Communiqué - 7 июля 2023 г
Это коммюнике первоначально появилось на Symfony Station .
Оживление вашего приложения Laravel: Понимание режима обслуживания
Оживление вашего приложения Laravel: Понимание режима обслуживания
Здравствуйте, разработчики! В сегодняшней статье мы рассмотрим важный аспект управления приложениями, который часто упускается из виду в суете...
Установка и настройка Nginx и PHP на Ubuntu-сервере
Установка и настройка Nginx и PHP на Ubuntu-сервере
В этот раз я сделаю руководство по установке и настройке nginx и php на Ubuntu OS.
Коллекции в Laravel более простым способом
Коллекции в Laravel более простым способом
Привет, читатели, сегодня мы узнаем о коллекциях. В Laravel коллекции - это способ манипулировать массивами и играть с массивами данных. Благодаря...
Как установить PHP на Mac
Как установить PHP на Mac
PHP - это популярный язык программирования, который используется для разработки веб-приложений. Если вы используете Mac и хотите разрабатывать...
0
2
883
1

Ответы 1

Попробуйте этот код. _shipping_instructions замените это на shipping_instructions

$shipping_instructions = get_post_meta($wpo_wcpdf->export->order >id,'shipping_instructions',true);
if (isset($shipping_instructions)) {
    echo $shipping_instructions;
}

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

8r3nd4n 19.03.2018 01:20

Другие вопросы по теме