Search code examples
phpvariablessessionwoocommercecheckout

Storing and using a variable to populate a shipping field in WooCommerce


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


Solution

  • Instead of storing the postcode in a session variable, you should first force guest users WC session initialization with the following:

    add_action( 'woocommerce_init', 'force_non_logged_user_wc_session' );
    function force_non_logged_user_wc_session(){ 
        if( is_user_logged_in() || is_admin() ) {
           return;
        }
    
        if ( isset(WC()->session) && ! WC()->session->has_session() ) {
           WC()->session->set_customer_session_cookie( true ); 
        }
    }
    

    Code goes in functions.php file of your child theme or in a plugin.

    Now you can set the postcode directly in your Step 1 from your defined $postcode variable using the following:

    WC()->customer->set_shipping_postcode( $postcode );
    

    And you don't need a step 2.