I have tried to do this myself using information from various sources but am running into issues which makes me think that it isn't the best or more appropriate way to do it.
I have a form to ask the users Postcode prior to the purchase of a product to ensure the product can be shipping to their area. If covered, the user can proceed to the checkout and for convenience (and security) the shipping Postcode field should be populated with their postcode.
This code is going into functions.php
Step 1 - get the postcode and add it to a session variable
[prior code gets the input - $postcode variable populated]
// Store the postcode for use later as a session
session_start();
_SESSION["stored_postcode"] = $postcode;enter code here
Step 2 - get the session variable and populate the shipping_postcode field
add_action( 'init', 'set_delivery_postcode' );
function set_delivery_postcode() {
session_start();
$delivery_postcode = @$_SESSION["stored_postcode"];
WC()->customer->set_shipping_postcode( sanitize_text_field( @$_POST['delivery_postcode'] ) );
}
But, for some reason this is causing an error with the theme and when I tried to login it says a critical error has occurred and I have to login in recovery mode.
The weird thing is though, it works and is actually populating the Postcode field in the checkout.
Is there anything obviously wrong with the above?
Your help is appreciated.
Rob
$delivery_postcodeand then never using it. And avoid the@silencer whenever possible. Instead prefer the null coalesce operator like$_SESSION["stored_postcode"] ?? null.