php - 在 WooCommerce 中为 guest 和客户设置字段中的邮政编码

标签 php jquery ajax wordpress woocommerce

主要思想是验证客人的邮政编码并根据它显示不同的消息。 我使用此线程设置运输代码:Set shipping postcode early before add to cart in 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");
      }
    });
  })
});

然后将该值传递给一个 PHP 函数,该函数应该将 postcode 值添加到访客 session 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();

}

我还构建了一个短代码函数来显示客人的 session 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 设置为访客 session customer_data。我试过直接在短代码中设置 postcode(使用相同的方法)并且它有效。

你能帮我找出问题所在吗? 我也很难调试 - 我怎么知道 session customer_data 已更改?

谢谢。

编辑:我已将客人的 session 客户数据发送到 AJAX 响应,我得到了这个:

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

这意味着数据是在 AJAX 响应后立即存储的。问题似乎是当我重新加载页面并再次尝试获取 guest session customer data 时未存储此数据。

最佳答案

您需要在 WC_Customer 对象上使用可用的 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 文件。经过测试并有效。

关于php - 在 WooCommerce 中为 guest 和客户设置字段中的邮政编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65717674/

相关文章:

ajax - 如何在每个页面可能从不同的偏移量开始时进行分页

javascript - JSON 编码 MySQL 数组并在 Google map 上显示

javascript - dygraph php 从数据库动态生成内容

javascript - Google Apps 脚本 HTML 应用程序中的 Google 图表

javascript - 通过javascript动态捕获textarea的大小

javascript - 最轻的单页刮刀

php - 电子邮件服务器;这种方法对垃圾邮件安全吗?

javascript - 如何在 javascript 和 laravel 中使用数据重定向路由

javascript - 通过 Ajax 发送 FormData + js 变量

javascript - 将HTML Table中的信息拆分并与 "header"信息合并