Search code examples
phpwordpresssessionwoocommercehook-woocommerce

How to display a $_SESSION variable in custom woocommerce checkout field?


I am able to verify by viewing the "Application" tab in the dev tools that my session variable has carried over to the checkout page; and I have the WC hook setup that allows me to change the "default"/value of the field I want to insert data into.

However, I am unable to get them to read each other.

add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

function custom_override_checkout_fields( $fields ) {
     $fields['order']['order_comments']['label'] = "Custom Neon Details (If included)";
     $fields['order']['order_comments']['default'] = $_SESSION["customtext"];
     var_dump( $fields );
     return $fields;
}

As you can see from the attached image, my session variable is present on that page. How now, do I get it to add that session variable to $fields['order']['order_comments']['default']?

Any help is appreciated! Thanks.

enter image description here


Solution

  • Use session_start(); before accessing the $_SESSION variable:

    add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
    function custom_override_checkout_fields( $fields ) {
    
        session_start();
    
        $fields['order']['order_comments']['label'] = "Custom Neon Details (If included)";
        $fields['order']['order_comments']['default'] = $_SESSION["customtext"];
        var_dump( $fields );
        return $fields;
    }
    

    Alternatively you can use jQuery with sessionStorage:

    // set the value of the order comment field via session storage
    add_action( 'wp_footer', 'set_value_order_comments_field_via_session_storage' );
    function set_value_order_comments_field_via_session_storage() {
        ?>
        <script type="text/javascript">
            jQuery(function($){
                var customtext = sessionStorage.getItem("customtext");
                if ( customtext.length ) {
                    $('#order_comments').val(customtext);
                }
            });
        </script>
        <?php
    }
    

    The code has been tested and works. Add it to your active theme's functions.php.