dongzhi2887
dongzhi2887
2019-02-07 23:38

使用保存在会话中的URL变量预填充Woocommerce登录字段

已采纳

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条回答

  • duanhanglekr37902 duanhanglekr37902 2年前

    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
    
    点赞 评论 复制链接分享