Woocommerce:如果将商品A添加到购物车,则商品B是可购买的

时间:2016-05-17 00:46:08

标签: php wordpress woocommerce

我试图修改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 );

我尝试了很多方法,但似乎没有任何效果。我该怎么做呢?

1 个答案:

答案 0 :(得分:0)

试试这个代码段。

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