Login & registration redirects - don't redirect login when on checkout page in WooCommerce

Viewed 234

My code works as expected but it should not redirect the user when they login while on the checkout page.

I used is_checkout() to try and detect this but it is not working as expected.

add_filter( 'woocommerce_login_redirect', 'bbloomer_customer_login_redirect', 9999, 2 );

function bbloomer_customer_login_redirect( $redirect ) {

    if ( is_checkout() ) {
        return '/checkout';
    } else {
        $redirect = '/my-account'; // custom URL same site
        return $redirect;
    }
}

// define the woocommerce_registration_redirect callback 
function filter_woocommerce_registration_redirect( $redirect ) { 
        $redirect = '/my-account'; // custom URL same site

        return $redirect;
 }

// add the filter 
add_filter( 'woocommerce_registration_redirect', 'filter_woocommerce_registration_redirect', 9999, 2 );
1 Answers

This should suffice

function filter_woocommerce_login_redirect( $redirect, $user ) {
    // Checkout 
    if ( $redirect == wc_get_checkout_url() ) {
        $redirect = '/checkout';
    } else {
        // Get the "My account" url
        $redirect = get_permalink( wc_get_page_id( 'myaccount' ) );
    }
    
    return $redirect;
}
add_filter( 'woocommerce_login_redirect', 'filter_woocommerce_login_redirect', 10, 2 );

function filter_woocommerce_registration_redirect( $redirect ) {
    // Get the "My account" url
    $redirect = get_permalink( wc_get_page_id( 'myaccount' ) );
    
    return $redirect;
}
add_filter( 'woocommerce_registration_redirect', 'filter_woocommerce_registration_redirect', 10, 1 );
Related