Musa Baltacı
Musa Baltacı

Reputation: 91

Redirection for non checkout guest allowed in WooCommerce

After Allow guest checkout for specific products only in WooCommerce answer to my previous question, the following code redirect users to login page:

add_action( 'template_redirect', 'checkout_redirect_non_logged_to_login_access');
function checkout_redirect_non_logged_to_login_access() {
    if( is_checkout() && !is_user_logged_in()){
        wp_redirect( get_permalink( get_option('woocommerce_myaccount_page_id') ) );
        exit;
    }
} 

But I have some products which allows guest checkout (see the linked question/answer above). So how could I fix my code for the products which allows guest checkout to disable that code redirection?

Upvotes: 1

Views: 359

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

You can replace my previous answer code with the following:

// Custom conditional function that checks if checkout registration is required
function is_checkout_registration_required() {
    if ( ! WC()->cart->is_empty() ) {
        // Loop through cart items
        foreach ( WC()->cart->get_cart() as $item ) {
            // Check if there is any item in cart that has not the option "Guest checkout allowed"
            if ( get_post_meta( $item['product_id'], '_allow_guest_checkout', true ) !== 'yes' ) {
                return true; // Found: Force checkout user registration and exit
            }
        }
    }
    return false;
}

add_filter( 'woocommerce_checkout_registration_required', 'change_tax_class_user_role', 900 );
function change_tax_class_user_role( $registration_required ) {
    return is_checkout_registration_required();
}

Then your current question code will be instead:

add_action( 'template_redirect', 'checkout_redirect_non_logged_to_login_access');
function checkout_redirect_non_logged_to_login_access() {
    if( is_checkout() && !is_user_logged_in() && is_checkout_registration_required() ){
        wp_redirect( get_permalink( get_option('woocommerce_myaccount_page_id') ) );
        exit;
    }
} 

Code goes in functions.php file of your active child theme (or active theme). It should works.

Upvotes: 2

Related Questions