WooCommerce의 게스트 및 고객에 대한 필드에서 우편 번호 설정

Jan 14 2021

주요 아이디어는 게스트의 우편 번호를 확인하고 그에 따라 다른 메시지를 표시하는 것입니다. 이 스레드를 사용하여 배송 코드를 설정 했습니다. WooCommerce에서 장바구니에 추가하기 전에 배송 우편 번호 를 미리 설정합니다.

랜딩 페이지의 입력 값을받는 작동하는 AJAX 요청을 작성했습니다.

jQuery(document).ready(function ($) {

  let postcodeField = jQuery("#postcode-field");
  let postcodeVal;

  postcodeField.on("change", function () {
    postcodeVal = postcodeField.val();
  });

  jQuery("#ph_btn").on("click", function () {

    var data = {
      action: 'postcode_handler',
      postcode: postcodeVal
    };

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    // If you need it on a public facing page, uncomment the following line:
    var ajaxurl = ph_script.ajax_url;

    jQuery.ajax({
      type: 'POST',
      url: ajaxurl,
      data: data,
      success: function (result) {
        // console.log(result);
      },
      error: function () {
        console.log("error");
      }
    });
  })
});

그런 다음이 값은 postcode게스트 세션에 값을 추가해야하는 PHP 함수에 전달됩니다 customer_data.

function my_AJAX_processing_function(){

    // Getting the postcode value
    $postcode = intval($_POST['postcode'] ); //Check if the input was a valid integer if ( $postcode == 0 ) {
        echo "Invalid Input";
            wp_die();
    }
    
    //Important: Early enable customer WC_Session 
    add_action( 'init', 'wc_session_enabler' );
    function wc_session_enabler() {
        if ( ! is_admin() && ! WC()->session->has_session() ) {
            WC()->session->set_customer_session_cookie( true );
        }
    }

    // Get an array of the current customer data stored in WC session
    $customer_data = (array) WC()->session->get('customer'); // Change the billing postcode $customer_data['postcode'] = $postcode; // Change the shipping postcode $customer_data['shipping_postcode'] = $postcode; // Save the array of customer WC session data WC()->session->set('customer', $customer_data);

    // Sending a response to the AJAX request
    echo($postcode);
    
    wp_die();

}

게스트의 세션을 표시하는 단축 기능도 구축했습니다 customer_data.

function shortcode_postcode_field(){

  // Getting the customer data from the session
  $customer_data = (array) WC()->session->get('customer');

  // Get the billing postcode
  // if ( isset( $customer_data['postcode'] ) ) $postcode = $customer_data['postcode']; // Showing the customer data for debug reasons var_dump($customer_data);

  return '
  <p class="form-row postcode-field on" id="postcode-field_field" data-priority="">
    <label for="postcode-field" class="">Code postal&nbsp;
      <span class="optional">(facultatif)</span>
    </label>
    <span class="woocommerce-input-wrapper">
      <input type="number" class="input-text" name="postcode" id="postcode-field" placeholder="85000" value="">
    </span>
    <button id="ph_btn" style="color: black">Vérifier son code postal</button>
    <p>Votre code postal est '.$postcode.'</p>
  </p>
  ';
}
add_shortcode( 'postcode-field', 'shortcode_postcode_field' );

문제는 AJAX 응답을받는 PHP 함수가 postcode게스트의 세션 으로 설정되지 않는 것 같습니다 customer_data. postcode동일한 방법으로 단축 코드 에서 직접 설정을 시도 했으며 작동합니다.

문제가 어디에 있는지 알아 내도록 도와 주시겠습니까? 또한 디버깅하는 데 어려움이 있습니다. 세션 customer_data이 변경되었음을 어떻게 알 수 있습니까?

감사합니다.

편집 : 게스트의 세션 customer data을 AJAX 응답으로 보냈고 다음 과 같이했습니다.

array(26) { ["id"]=> string(1) "0" ... ["postcode"]=> int(44500) ... }

이는 데이터가 AJAX 응답 직후에 저장됨을 의미합니다. 문제는 페이지를 다시로드하고 게스트의 세션을 customer data다시 가져 오려고 할 때이 데이터가 저장되지 않는 것 같습니다 .

답변

2 LoicTheAztec Jan 14 2021 at 20:16

다음 WC_Customer과 같이 Object 에서 사용 가능한 setter 및 getter 메서드를 대신 사용해야합니다 .

  • WC()->customer->get_billing_postcode() 또는 WC()->customer->get_shipping_postcode()
  • WC()->customer->set_billing_postcode() 또는 WC()->customer->set_shipping_postcode()

이제 코드에 몇 가지 실수가 있습니다. 다음과 같이 모든 코드를 다시 검토했습니다.

// Early enable customer WC_Session
add_action( 'init', 'wc_session_enabler' );
function wc_session_enabler() {
    if ( ! is_admin() && ! WC()->session->has_session() ) {
        WC()->session->set_customer_session_cookie( true );
    }
}

// Shortcode
add_shortcode( 'postcode-field', 'shortcode_postcode_field' );
function shortcode_postcode_field(){
    return '<p class="form-row postcode-field on" id="postcode-field_field" data-priority="">
        <label for="postcode-field" class="">' . __("Postcode", "woocommerce") . '&nbsp;
            <span class="optional">(optional)</span>
        </label>
        <span class="woocommerce-input-wrapper">
            <input type="number" class="input-text" name="postcode-input" id="postcode-input" placeholder="85000" value="">
        </span>
        <button id="postcode-submit" name="postcode-submit" class="button alt">' . __("Check your postcode", "woocommerce") . '</button>
        <br><div class="postcode-message" style="display:none"></div>
    </p>';
}

// Jquery (Ajax sender)
add_action( 'wp_footer', 'postcode_field_js_script' );
function postcode_field_js_script() {
    ?>
    <script type="text/javascript">
    jQuery( function($) { var postcode = ''; $('#postcode-input').on("input change", function () {
            postcode = $(this).val(); }); $("#postcode-submit").on('click', function () {
            $.ajax({ type: 'POST', url: '<?php echo admin_url('/admin-ajax.php'); ?>', data: { 'action': 'postcode_receiver', 'postcode': postcode }, success: function (response) { $('.postcode-message').html(response).show(300);
                    // console.log(response);
                },
                error: function (error) {
                    $('.postcode-message').html(error).show(300); // console.log(error); } }); }); }); </script> <?php } // Php (Ajax receiver) - Check and set the postcode - return message (notice) add_action('wp_ajax_postcode_receiver', 'postcode_receiver'); add_action('wp_ajax_nopriv_postcode_receiver', 'postcode_receiver' ); function postcode_receiver(){ if( isset($_POST['postcode']) ) {
        $postcode = sanitize_text_field($_POST['postcode']);

        if ( $postcode > 0 ) { WC()->customer->set_shipping_postcode($postcode);
            WC()->customer->set_billing_postcode($postcode); $saved_postcode = WC()->customer->get_shipping_postcode();

            echo sprintf( '<span style="color:green;">' . __("Your postcode %s has been registered successfully.", "woocommerce") . '</span>', '"' . $saved_postcode . '"' );
        } else {
            echo '<span style="color:red;">' . __("Check your postcode input please.", "woocommerce") . '</span>';
        }
        wp_die();
    } else {
        echo '<span style="color:red;">' . __("A problem has occurred, try later.", "woocommerce") . '</span>';
        wp_die();
    }
}

코드는 활성 자식 테마 (또는 활성 테마)의 functions.php 파일에 들어갑니다. 테스트 및 작동합니다.