我想应用以下两种情况:
- 如果用户没有登录,购物车是空的:然后重定向用户登录,然后是我的帐户
- 如果用户未登录且购物车中有产品:则将用户重定向到登录,登录后重定向到结帐
My Code:
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 ) {}
检查购物车时,我的网站停止工作。
我已经在主题的functions.php文件中添加了这段代码。
我做错了什么?
为避免站点关闭,缺少
global $woocommerce;
。
现在global $woocommerce;
和$woocommerce->cart
现在简单地用WC()->cart
代替。检查购物车是否为空,应该使用
WC()->cart->is_empty()
,因为is_empty()
是WC_cart
类的条件方法。之后,在结帐页面(在两种情况下),如果用户没有登录,您希望将他重定向到my_account页面(登录/创建帐户区域)。
现在在my_account页面上,当登录用户的购物车中有东西时,您希望将他重定向到结帐页面。
下面是你需要的代码:
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类
WC_Cart
-is_empty()
方法 - WooCommerce可用条件标签