Hel*_*nds 2 php wordpress checkout cart woocommerce
我想申请以下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');
Run Code Online (Sandbox Code Playgroud)
以上代码适用于我的第一个案例.但对于我的第二种情况,当我检查购物车时if ( sizeof( $woocommerce->cart->cart_contents ) == 0 ) {},我的网站停止工作.
我在我的主题的functions.php文件中添加了这段代码.
我做错了什么?
Loi*_*tec 11
为了避免您的网站关闭,
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') ) );
}
Run Code Online (Sandbox Code Playgroud)
代码放在活动子主题的function.php文件中.经过测试和工作.
参考(Woocommerce文档):
| 归档时间: |
|
| 查看次数: |
3211 次 |
| 最近记录: |