Woocommerce: Item B is purchasable if item A added to the cart

I was trying to modify the WooCommerce Is_Purchasable option so that, item B is purchasable if item A is added to the cart.

I managed to disable add-to-cart button for item B with the code below. But when item A is added to the cart, the page won’t load.

Read More

Here’s the code:

function wc_product_is_in_the_cart( $ids ) {
    $cart_ids = array();
    foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
        $cart_product = $values['data'];
        $cart_ids[]   = $cart_product->id;
    }
    if ( ! empty( array_intersect( $ids, $cart_ids ) ) ) {
        return true;
    } else {
        return false;
    }
}
function wc_product_is_purchasable ( $is_purchasable, $product ) {
        $product_ids = array( '249' );
    if ( ! wc_product_is_in_the_cart( $product_ids ) ) {
       return ($product->id == 2983 ? false : $is_purchasable);
    }
    return $is_purchasable;
}
add_filter( 'woocommerce_is_purchasable', 'wc_product_is_purchasable', 10, 2 );

I’ve tried a bunch of ways, but nothing seems working. How should I go on with this?

Related posts

1 comment

  1. Try this snippet.

    function wc_product_is_purchasable ( $is_purchasable, $product ) {
        /* List of product ids that must be in the cart 
         * in order to make the particular product purchasable */
        $product_ids = array( '249' );
        // The actual product, on which the purchasable status should be determined
        $concerned_pid = 2983;
    
        if( $product->id == $concerned_pid ) {
            // make it false
            $is_purchasable = false;
            // get the cart items object
            $cart_items = WC()->cart->get_cart();
            foreach ( $cart_items as $key => $item ) {
                // do your condition
                if( in_array( $item["product_id"], $product_ids ) ) {
                    // Eligible product found on the cart 
                    $is_purchasable = true;
                    break;
                }
            }   
        }
    
        return $is_purchasable;
    }
    
    add_filter( 'woocommerce_is_purchasable', 'wc_product_is_purchasable', 99, 2 );
    

Comments are closed.