我想申请以下2个案例:
我的代码:
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文件中添加了此代码。
我做错了什么?
答案 0 :(得分:9)
为避免您的网站关闭,
global $woocommerce;
丢失了。
现在,global $woocommerce;
$woocommerce->cart
现已完全由WC()->cart
替换。要检查购物车是否为空,您应该使用
WC()->cart->is_empty()
,因为is_empty()
是WC_cart
class的条件方法。在结帐页面之后(在两种情况下)如果用户未登录,您需要将其重定向到 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文档):