0
votes

I am using "Pre-fill Woocommerce checkout fields with Url variables saved in session" answer code, trying to populate Woocommerce login username and password with variables saved in session.

This is my customized code in functions.php so far:

// Save user data from URL to Woocommerce session, this works fine
add_action( 'template_redirect', 'set_custom_data_wc_session' );
function set_custom_data_wc_session () {
    if ( isset( $_GET['sliced_client_email'] ) || isset( $_GET['tu_name'] ) ) {
        $email   = isset( $_GET['sliced_client_email'] )   ? esc_attr( $_GET['sliced_client_email'] )   : '';
        $pw = isset( $_GET['password'] ) ? esc_attr( $_GET['password'] ) : '';

        // Set the session data
        WC()->session->set( 'custom_data', array( 'email' => $email, 'password' => $pw ) );
    }
}

// Autofill checkout fields from user data saved in Woocommerce session, this is my problem
add_filter( 'woocommerce_login_form' , 'prefill_login_fields' );
function prefill_login_fields ( $xxx ) {
    // Get the session data
    $data = WC()->session->get('custom_data');

    // Email
    if( isset($data['email']) && ! empty($data['email']) )
       $xxx['username']['default'] = $data['email'];

    // Password
    if( isset($data['password']) && ! empty($data['password']) )
        $xxx['password']['default'] = $data['password'];
}

But of course I can't find the parameters to populate. On the checkout page there is $address_fields['billing_email'] but I can't find a similar parameter for the login page. Not sure what to put in $xxx and $xxx['username']['default'] and $xxx['password']['default'].

Thanks for the help!!

1
Or if there is another way to simply get login fields pre-filled from URL parameters, they don't necessarily have to be stored in saved session.Phoebe
I don't think that you can pre-populate the password field anyway as it's a password field that needs to be manually inputed. The only possible way should be to use Javascript / jQuery as those fields are hard coded in global/form-login.php template, and the linked answer code mentioned can't work on that case.LoicTheAztec
Thanks for the tip, I found a solution using jQuery.Phoebe

1 Answers

0
votes

Alright so instead of using variables stored in session, I found a simple jQuery solution.

add_action('woocommerce_login_form','woocommerce_js_2');

function woocommerce_js_2()
{ // break out of php 
?>
<script>
// Setup a document ready to run on initial load
jQuery(document).ready(function($) {
    var r = /[?|&](\w+)=(\w+)+/g;  //matches against a kv pair a=b
    var query = r.exec(window.location.href);  //gets the first query from the url
    while (query != null) {

            //index 0=whole match, index 1=first group(key) index 2=second group(value)
        $("input[name="+ query[1] +"]").attr("value",query[2]);

        query = r.exec(window.location.href);  //repeats to get next capture
    }

});
</script>
<?php } // break back into php