dsj8000 2016-09-06 18:53
浏览 93
已采纳

基于购物车的WooCommerce登录重定向

I want to apply following 2 case :

  • If User not logged in and cart is empty: Then redirect user to login and then my account
  • If User not logged in and cart has product: Then redirect user to login and after login redirect to checkout

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');

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.

I have added this code in my theme's functions.php file.

What I am doing wrong?

  • 写回答

1条回答 默认 最新

  • dongpu1879 2016-09-06 20:50
    关注

    To avoid your site to be off, global $woocommerce; is missing.
    Now global $woocommerce; with $woocommerce->cart is now simply replaced by 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.

    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).

    Now on my_account page, when a logged user has something in his cart, you want to redirect him on checkout page.

    Here is the code you need:

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

    Code goes in function.php file of your active child theme. Tested and works.


    Reference (Woocommerce documentation):

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号