0

I am trying to send out emails to my customers and allow them one click to reset passwords with their email pre-filled on the reset password page by URL /account/lost-password/?email=123@gmail.com

However, I am not sure how to make it right. Here is my code. Thanks!

add_action( 'template_redirect', 'set_custom_data_wc_session' );
function set_custom_data_wc_session () {
    if ( isset( $_GET['email'] )  ) {
        $em   = isset( $_GET['email'] )   ? esc_attr( $_GET['email'] )   : '';
        // Set the session data
        WC()->session->set( 'custom_data', array( 'email' => $em ) );
    }
}

add_filter( 'woocommerce_login_form' , 'prefill_login_form' );
function prefill_login_form ( $fields ) {
    // Get the session data
    $data = WC()->session->get('custom_data');

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

    return $fields;
}
Blue Li
  • 41
  • 6
  • I am not sure... I found it from this thread https://stackoverflow.com/questions/54583999/pre-fill-woocommerce-login-fields-with-url-variables-saved-in-session https://stackoverflow.com/questions/50356459/pre-fill-woocommerce-checkout-fields-with-url-variables-saved-in-session So I tried woocommerce_lost_password_form does not seem right either.. I see the reset password field id is #user_login. I thought they were the same.. – Blue Li Aug 17 '22 at 15:01
  • 1
    Well, as you can see from the similar answers you refer to. It can be done entirely via code (read as via a hook) but then you also will have to use some extra jQuery and that is rather 'a dirty solution' or you have to overwrite the template file, the correct solution in this case. – 7uc1f3r Aug 18 '22 at 13:11
  • @7uc1f3r Yes you are right, the jQuery works. I only need to change the hook and the regex. Thanks – Blue Li Aug 18 '22 at 16:04

1 Answers1

0

I managed to do it by referencing this thread Pre-fill Woocommerce login fields with URL variables saved in session

<?php
add_action('woocommerce_lostpassword_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 r = /[?|&](\w+)=([\w.-]+@[\w.-]+)/g;
    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
Blue Li
  • 41
  • 6