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

问题描述:

我试图修改WooCommerce Is_Purchasable选项,以便如果商品A被添加到购物车中,则商品B是可购买的。Woocommerce:如果商品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); 

我已经尝试了一堆的方法,但似乎没有任何工作。我应该如何继续?

+0

Ahyat相反WC()的' - > cart-> get_cart()'萨克的代码,试图通过'WC()来代替它 - > cart-> cart_contents' ......请告诉我,如果它的工作......谢谢。 – LoicTheAztec

试试这个片段。

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

添加到购物车按钮被删除,但它会给结账时500内部错误。 – Ahyat

+0

这里是在错误日志中:PHP致命错误:调用线504上functions.php中null的成员函数get_cart() – Ahyat