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;
}