更新:是不可能的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個以上屬性值。
唯一令人討厭的是,我無法刪除經典添加到購物車通知目前。 我會盡量找到另一種方式...
非常感謝!這正是我正在尋找的。 它看起來是正確的,但它是在網站上的越野車。例如,當我的購物籃爲空時,我嘗試添加產品時,收到一條錯誤消息,指出網站現在無法處理該請求。當我禁用片段,然後添加到購物車時,它工作正常。當我再次激活片段並從第三個供應商添加項目時,我看到彈出消息顯示「對不起,沒有產品符合您的選擇,請選擇其他組合。」 任何想法爲什麼這樣做? –
謝謝@LoicTheAztec 快速更新 - 我不再收到「對不起沒有產品...」彈出。當我的購物車爲空時,我仍收到「網站無法處理請求」錯誤消息。當停用PHP時,添加一個產品,然後重新激活代碼,我可以添加儘可能多的產品,而不會發生任何事情。我已經仔細閱讀了你發給我的代碼,看起來很穩固。問題可能在網站的其他地方嗎? –
@CraigdeGouveia我發現了另一種方式來做到這一點...看到我更新的答案...謝謝。 – LoicTheAztec