WooCommerce - 登录后重定向到上一页

2024-02-18

我一直在寻找可以处理它几个小时的插件和片段,但没有成功。每个答案都不适合我。我的菜单中有“登录”链接,可通往 WooCommerce“我的帐户”页面,其中显示登录表单。我希望客户在成功登录后返回到单击“登录”链接的页面。

wp_get_referer()不返回任何内容并且$_SERVER["HTTP_REFERER"]如果放入挂钩的函数中,则返回我的帐户页面woocommerce_login_redirect(我使用 PHP 调试控制台来检查)。

这是我的代码:

// Redirect user after login.
add_filter( 'woocommerce_login_redirect', 'wc_custom_user_redirect', 10, 2 );
function wc_custom_user_redirect( $redirect, $user ) {
    // Get the first of all the roles assigned to the user
    $role = $user->roles[0];
    $dashboard = admin_url();       

    if (in_array($role, array('administrator', 'shop_manager', 'editor', 'author', 'contributor'))) {
        $redirect = $dashboard;         
    } elseif (in_array($role, array('customer', 'subscriber'))) {
        $redirect = $_SERVER["HTTP_REFERER"];          
    } else {
        $redirect = $_SERVER["HTTP_REFERER"];       
    }

    return $redirect;

}

这是我使用的过滤器出现在 WooCommerce 代码中的位置:

/** 
   * Process the login form. 
   */ 
  public static function process_login() { 
      $nonce_value = isset( $_POST['_wpnonce'] ) ? $_POST['_wpnonce'] : ''; 
      $nonce_value = isset( $_POST['woocommerce-login-nonce'] ) ? $_POST['woocommerce-login-nonce'] : $nonce_value; 

      if ( ! empty( $_POST['login'] ) && wp_verify_nonce( $nonce_value, 'woocommerce-login' ) ) { 

          try { 
              $creds = array( 
                  'user_password' => $_POST['password'],  
                  'remember' => isset( $_POST['rememberme'] ),  
 ); 

              $username = trim( $_POST['username'] ); 
              $validation_error = new WP_Error(); 
              $validation_error = apply_filters( 'woocommerce_process_login_errors', $validation_error, $_POST['username'], $_POST['password'] ); 

              if ( $validation_error->get_error_code() ) { 
                  throw new Exception( '<strong>' . __( 'Error:', 'woocommerce' ) . '</strong> ' . $validation_error->get_error_message() ); 
              } 

              if ( empty( $username ) ) { 
                  throw new Exception( '<strong>' . __( 'Error:', 'woocommerce' ) . '</strong> ' . __( 'Username is required.', 'woocommerce' ) ); 
              } 

              if ( is_email( $username ) && apply_filters( 'woocommerce_get_username_from_email', true ) ) { 
                  $user = get_user_by( 'email', $username ); 

                  if ( isset( $user->user_login ) ) { 
                      $creds['user_login'] = $user->user_login; 
                  } else { 
                      throw new Exception( '<strong>' . __( 'Error:', 'woocommerce' ) . '</strong> ' . __( 'A user could not be found with this email address.', 'woocommerce' ) ); 
                  } 
              } else { 
                  $creds['user_login'] = $username; 
              } 

              // On multisite, ensure user exists on current site, if not add them before allowing login. 
              if ( is_multisite() ) { 
                  $user_data = get_user_by( 'login', $username ); 

                  if ( $user_data && ! is_user_member_of_blog( $user_data->ID, get_current_blog_id() ) ) { 
                      add_user_to_blog( get_current_blog_id(), $user_data->ID, 'customer' ); 
                  } 
              } 

              // Perform the login 
              $user = wp_signon( apply_filters( 'woocommerce_login_credentials', $creds ), is_ssl() ); 

              if ( is_wp_error( $user ) ) { 
                  $message = $user->get_error_message(); 
                  $message = str_replace( '<strong>' . esc_html( $creds['user_login'] ) . '</strong>', '<strong>' . esc_html( $username ) . '</strong>', $message ); 
                  throw new Exception( $message ); 
              } else { 

                  if ( ! empty( $_POST['redirect'] ) ) { 
                      $redirect = $_POST['redirect']; 
                  } elseif ( wp_get_referer() ) { 
                      $redirect = wp_get_referer(); 
                  } else { 
                      $redirect = wc_get_page_permalink( 'myaccount' ); 
                  } 

                  wp_redirect( apply_filters( 'woocommerce_login_redirect', $redirect, $user ) ); 
                  exit; 
              } 
          } catch ( Exception $e ) { 
              wc_add_notice( apply_filters( 'login_errors', $e->getMessage() ), 'error' ); 
              do_action( 'woocommerce_login_failed' ); 
          } 
      } 
  } 

我尝试了 @dineshkashera 的答案,但它抛出了一个错误,因为启动会话不是一个好的做法,而且 wp_get_referer 钩子也不起作用,因此 $_SERVER['HTTP_REFERER'] 。

所以我唯一的解决方案是创建一个 cookie 来保存我们之前的链接。

这是我的代码:

//First we need to set a cookie that will save the previous url
setcookie('nlcrc', $_SERVER['HTTP_REFERER'], time() + 86000, COOKIEPATH, COOKIE_DOMAIN, false);

//Then initiate Woocommerce redirect hook

//This is for the WC login redirect
add_filter('woocommerce_login_redirect', 'wcc_redirects', 9999, 2);

//I have added also WC registration redirect
add_filter('woocommerce_registration_redirect', 'wcc_redirects', 9999, 1);

//Then this will be the handler
function wcc_redirects ($redirect) {
    if (isset($_COOKIE['nlcrc'])) {
        $redirect = $_COOKIE['nlcrc'];
        return $redirect;
    } else {
        $redirect = home_url();
        return $redirect;
    }
}

或者你也可以使用 Javascript 来快速而肮脏地进行操作。如果您的默认登录页面是 Woocommerce 我的帐户页面。

add_filter('woocommerce_login_redirect', 'wc_cstm_login_redirect', 99 );

function wc_cstm_login_redirect () {
    echo "<script type='text/javascript'>
    history.go(-2);
    </script>";
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WooCommerce - 登录后重定向到上一页 的相关文章

随机推荐