問題描述
我想申請以下兩種情況:
I want to apply following 2 case :
- 如果用戶未登錄且購物車為空:然后重定向用戶登錄,然后重定向我的帳戶
- 如果用戶未登錄并且購物車有產品:然后重定向用戶登錄,登錄后重定向到結帳
我的代碼:
function wpse_Nologin_redirect() {
if (
! is_user_logged_in()
&& (is_checkout())
) {
// feel free to customize the following line to suit your needs
$MyLoginURL = "http://example.in/my-account/";
wp_redirect($MyLoginURL);
exit;
}
}
add_action('template_redirect', 'wpse_Nologin_redirect');
以上代碼在我的第一種情況下運行良好.但是對于我的第二種情況,當我使用 if ( sizeof( $woocommerce->cart->cart_contents ) == 0 ) {}
檢查購物車時,我的網站停止在職的.
Above code is working fine for my first case. But for my second case, when I check cart with if ( sizeof( $woocommerce->cart->cart_contents ) == 0 ) {}
, my site stops working.
我已將此代碼添加到我的主題的functions.php 文件中.
I have added this code in my theme's functions.php file.
我做錯了什么?
推薦答案
為避免您的網站關閉,
global $woocommerce;
缺失.
現在帶有$woocommerce->cart
的global $woocommerce;
現在簡單地替換為WC()->cart
.
To avoid your site to be off,
global $woocommerce;
is missing.
Nowglobal $woocommerce;
with$woocommerce->cart
is now simply replaced byWC()->cart
.
要檢查購物車是否為空,您應該使用 WC()->cart->is_empty()
,如 is_empty()
是 WC_cart
類.
To check if cart is empty, you should use WC()->cart->is_empty()
, as is_empty()
is a conditional method of WC_cart
class.
之后,在結帳頁面(在兩種情況下)如果用戶未登錄,您希望將他重定向到 my_account 頁面(登錄/創(chuàng)建帳戶區(qū)域).
After, on checkout page (in both cases) if user is not logged in, you want to redirect him to my_account page (login/create account area).
現在在 my_account 頁面,當登錄用戶的購物車中有東西時,您希望將他重定向到結帳頁面.
Now on my_account page, when a logged user has something in his cart, you want to redirect him on checkout page.
這是您需要的代碼:
add_action('template_redirect', 'woocommerce_custom_redirections');
function woocommerce_custom_redirections() {
// Case1: Non logged user on checkout page (cart empty or not empty)
if ( !is_user_logged_in() && is_checkout() )
wp_redirect( get_permalink( get_option('woocommerce_myaccount_page_id') ) );
// Case2: Logged user on my account page with something in cart
if( is_user_logged_in() && ! WC()->cart->is_empty() && is_account_page() )
wp_redirect( get_permalink( get_option('woocommerce_checkout_page_id') ) );
}
代碼位于活動子主題的 function.php 文件中.經過測試并有效.
參考(Woocommerce 文檔):
- Woocommerce Class
WC_Cart
—is_empty()
方法 - WooCommerce 可用的條件標簽
- Woocommerce Class
WC_Cart
—is_empty()
method - WooCommerce Available conditional tags
這篇關于基于購物車的 WooCommerce 登錄重定向的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!