Woocommerce is_purchasable hook for variable products Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Woocommerce is_purchasable hook for variable products without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m using the below code to make all products on woocommerce not purchasable unless the user is signed in.

function et_remove_atc(){
    
        
    if( ! is_user_logged_in() ){
    
        return false;
    
    }else{
        
        return true;
        
    }
    
}

add_filter( 'woocommerce_is_purchasable', 'et_remove_atc' );

This only works for simple products and not variable products. I’ve tried to add the below additional filter, but this doesn’t work.

add_filter( 'woocommerce_variation_is_purchasable', 'et_remove_atc', 10, 2 );

What am I missing?

Answer

You are using the right hook for variable products and its variations. Note that the add to cart button on variable products will stay grayed (disabled) for guests. If it is not the case, it can be due to a plugin, your theme customizations or some other customizations made by you.

The correct code to be used is:

add_filter( 'woocommerce_is_purchasable', 'avoid_guest_purchases' );
add_filter( 'woocommerce_variation_is_purchasable', 'avoid_guest_purchases' );
function avoid_guest_purchases( $is_purchasable ){
    if( ! is_user_logged_in() ){
        return false;
    }
    return $is_purchasable;
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.


To remove variable add to cart button (on single product pages) for guests, use the following:

add_action( 'woocommerce_single_product_summary', 'remove_variable_add_to_cart_button', 1 );
function remove_variable_add_to_cart_button() {
    global $product;

    // For variable product types (keeping attribute select fields)
    if( $product->is_type( 'variable' ) && is_user_logged_in() ) {
        remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 );
    }
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

We are here to answer your question about Woocommerce is_purchasable hook for variable products - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji