2017-08-09 33 views
2

我發現了類似的解決方案,例如:「如何限制訂單到一個類別」。我試圖修改代碼,但它不夠具體。阻止客戶從Woocommerce中的3個以上供應商訂購

就我而言,每個供應商都由一個產品屬性值8條款來定義。如果購物車包含來自3個以上不同條款的產品,則需要設置一條消息,指出「對不起,您只能同時從3個不同的供應商處訂購」。

這是我使用的是什麼爲出發點:

add_action('woocommerce_add_to_cart', 'three_vendors'); 
function three_vendors() { 

    if ATTRIBUTE = SELECT A VENDOR; NUMBER OF TERMS > 3 { 

    echo "Sorry! You can only order from 3 Vendors at a time.」; 

    } 
} 

中間線是我填充使用非PHP語言的空白。

我正在尋找一種方法來定義購物車中的變化量。如果這不適用於屬性,我可以改爲使用類別。

有誰知道如何做到這一點?

回答

1

更新:是不可能的woocommerce_add_to_cart_valisation鉤來管理變化

相反,我們可以使用woocommerce_add_to_cart過濾鉤子鉤住一個自定義的功能,去掉最後加入購物車中物品時更超過3個供應商(物品)在購物車中:

// Remove the cart item and display a notice when more than 3 values for "pa_vendor" attibute. 
add_action('woocommerce_add_to_cart', 'no_more_than_three_vendors', 10, 6); 

function no_more_than_three_vendors($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) { 

    // Check only when there is more than 3 cart items 
    if (WC()->cart->get_cart_contents_count() < 4) return; 

    // SET BELOW your attribute slug… always begins by "pa_" 
    $attribute_slug = 'pa_vendor'; // (like for "Color" attribute the slug is "pa_color") 

    // The current product object 
    $product = wc_get_product($variation_id); 
    // the current attribute value of the product 
    $curr_attr_value = $product->get_attribute($attribute_slug); 

    // We store that value in an indexed array (as key /value) 
    $attribute_values[ $curr_attr_value ] = $curr_attr_value; 

    //Iterating through each cart item 
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) { 

     // The attribute value for the current cart item 
     $attr_value = $cart_item[ 'data' ]->get_attribute($attribute_slug); 

     // We store the values in an array: Each different value will be stored only one time 
     $attribute_values[ $attr_value ] = $attr_value; 
    } 
    // We count the "different" values stored 
    $count = count($attribute_values); 

    // if there is more than 3 different values 
    if($count > 3){ 
     // We remove last cart item 
     WC()->cart->remove_cart_item($cart_item_key); 
     // We display an error message 
     wc_clear_notices(); 
     wc_add_notice(__("Sorry, you may only order from 3 different Vendors at a time. This item has been removed", "woocommerce"), 'error'); 
    } 
} 

代碼在你的活動子主題(或主題)的function.php文件中,或者也在任何插件文件中。

此代碼已經過測試,應該適合您。它將檢查與您的特定屬性有關的屬性值,並將刪除最後添加的購物車項目的3個以上屬性值。

唯一令人討厭的是,我無法刪除經典添加到購物車通知目前。 我會盡量找到另一種方式...

+0

非常感謝!這正是我正在尋找的。 它看起來是正確的,但它是在網站上的越野車。例如,當我的購物籃爲空時,我嘗試添加產品時,收到一條錯誤消息,指出網站現在無法處理該請求。當我禁用片段,然後添加到購物車時,它工作正常。當我再次激活片段並從第三個供應商添加項目時,我看到彈出消息顯示「對不起,沒有產品符合您的選擇,請選擇其他組合。」 任何想法爲什麼這樣做? –

+0

謝謝@LoicTheAztec 快速更新 - 我不再收到「對不起沒有產品...」彈出。當我的購物車爲空時,我仍收到「網站無法處理請求」錯誤消息。當停用PHP時,添加一個產品,然後重新激活代碼,我可以添加儘可能多的產品,而不會發生任何事情。我已經仔細閱讀了你發給我的代碼,看起來很穩固。問題可能在網站的其他地方嗎? –

+0

@CraigdeGouveia我發現了另一種方式來做到這一點...看到我更新的答案...謝謝。 – LoicTheAztec

相關問題