WooCommerce 允許用户在 My Account 頁面登錄或註冊,成功後都會跳轉到 My Account 頁面。本文用一個實例介紹如何更改這個默認行為。例如要求用户必須登錄才能結賬時,先跳轉到 My Account 頁面完成信息認證,成功後直接跳到結賬頁面完成購買。
首先,修改登錄/註冊表單
找到 WooCommerce/templates/myaccount/form-login.php,拷貝到主題目錄/WooCommerce/myaccount/form-login.php 。
打開 form-login.php,加入獲取 redirect 地址的代碼,位置如下所示
<?php do_action('WooCommerce_before_customer_login_form'); ?>
<?php $redirect = $_REQUEST['redirect_to']; ?>
然後分別在登錄和註冊表單的提交按鈕前加入隱藏字段,記錄轉向地址。
<input type="hidden" name="redirect" value="<?php echo esc_url( $redirect ) ?>" /> <input type="submit" class="button" name="login" value="<?php _e( 'Login', 'WooCommerce' ); ?>" />
<input type="hidden" name="redirect" value="<?php echo esc_url( $redirect ) ?>" /> <input type="submit" class="button" name="register" value="<?php _e( 'Register', 'WooCommerce' ); ?>" />
強制訪問 checkout 的 guest 用户登錄
在主題的 functions.php 中加入如下代碼
add_action( 'WooCommerce_before_checkout_form', 'theme_wc_redirect_guest_user' );
function theme_wc_redirect_guest_user(){
if( !is_user_logged_in() ) {
$checkout_url = get_permalink( WooCommerce_get_page_id('checkout') );
$args['redirect_to'] = urlencode( $checkout_url );
$login_url = add_query_arg( $args, get_permalink( WooCommerce_get_page_id('myaccount') ) );
wp_safe_redirect($login_url);
}
}
最後,加入註冊跳轉功能
登錄表單只要有 redirect 這個隱藏字段,就能自動跳轉,註冊表單不行,所以在主題的 functions.php 中加入如下代碼。
add_filter ( 'WooCommerce_registration_redirect', 'theme_wc_registration_redirect' );
function theme_wc_registration_redirect( $redirect ) {
if ( $_POST['redirect'] ) {
$redirect = $_POST['redirect'];
}
return $redirect;
}