2016-05-17 69 views
1

我試圖修改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

回答

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

添加到購物車按鈕被刪除,但它會給結賬時500內部錯誤。 – Ahyat

+0

這裏是在錯誤日誌中:PHP致命錯誤:調用線504上functions.php中null的成員函數get_cart() – Ahyat

相關問題