WooCommerce login redirect based on cart and based on path

时光总嘲笑我的痴心妄想 提交于 2019-12-11 16:22:59

问题


I want these two cases, how can i achieve that

User Checkout > Check login > if logged in checkout. if not Redirect to login/register page > proceed to the checkout page.

After 2nd (From checkout page) point if customer want to go to my account then take them to My Account page if clicking on My Account link even if cart having items

Scenario 2 if customer login directly without redirecting from any url > My Account Page have to show.

How can i achieve that .

I followed the above question but issue i am facing to achieve my requirements.

WooCommerce login redirect based on cart

Code 1

add_action('template_redirect','check_if_logged_in');
function check_if_logged_in()
{
    $pageid = 8; // your checkout page id
    if(!is_user_logged_in() && is_page($pageid))
    {
        $url = add_query_arg(
            'redirect_to',
            get_permalink($pagid),
            site_url('/my-account/') // your my acount url
        );
        wc_add_notice( 'Please Login for Checkout', 'notice' );
        wp_redirect($url);
        exit;
    }
}

Code 2

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

Expecting output as User Checkout > Check login > if logged in checkout. if not Redirect to login/register page > proceed to the checkout page. Checkout page > My- Account have to work if any user want to go to my account page either having products in cart.

Second

If user logged in normally then Show them my-account only don't redirect to checkout

来源:https://stackoverflow.com/questions/56071005/woocommerce-login-redirect-based-on-cart-and-based-on-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!