Solution:
You need to use instead available setter and getter methods on the WC_Customer
Object like:
WC()->customer->get_billing_postcode()
orWC()->customer->get_shipping_postcode()
WC()->customer->set_billing_postcode()
orWC()->customer->set_shipping_postcode()
Now there are some mistakes in your code. I have revisited all your code as follows:
// 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") . '
<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();
}
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.