【问题标题】:Set postcode from a field for guests and customers in WooCommerce在 WooCommerce 中为客人和客户的字段设置邮政编码
【发布时间】:2021-04-19 09:29:05
【问题描述】:

主要思想是验证客人的邮政编码并据此显示不同的信息。 我已经使用这个线程来设置运输代码: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 值添加到访客会话 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 时,此数据未存储。

【问题讨论】:

    标签: php jquery ajax wordpress woocommerce


    【解决方案1】:

    您需要在 WC_Customer 对象上使用可用的 setter 和 getter 方法,例如:

    • WC()-&gt;customer-&gt;get_billing_postcode()WC()-&gt;customer-&gt;get_shipping_postcode()
    • WC()-&gt;customer-&gt;set_billing_postcode()WC()-&gt;customer-&gt;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 文件中。经过测试并且可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2012-07-10
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 2016-10-20
      相关资源
      最近更新 更多