Woocommerce:如果物品A添加到购物车中,则可以购买物品B


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

我试图修改WooCommerce Is_Purchasable选项,这样,如果项目A添加到购物车中,项目B就可以购买。

我用下面的代码禁用了项目B的添加到购物车按钮。但当项目A添加到购物车时,页面将不会加载。

这是代码:

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

我尝试了很多方法,但似乎都不起作用。我该怎么做?

试试这个片段。

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