gpt4 book ai didi

php - 防止客户从 Woocommerce 中超过 3 个供应商处订购

转载 作者:行者123 更新时间:2023-12-04 03:10:34 26 4
gpt4 key购买 nike

我找到了类似的解决方案,例如:“如何将订单限制在一个类别中”。我尝试修改代码,但它不够具体。

在我的例子中,每个供应商都是由一个产品属性值定义的,总共有 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语言填空

我正在寻找一种方法来定义购物车中的变化量。如果属性无法做到这一点,我愿意改用类别。

有人知道怎么做吗?

最佳答案

Update: Is not possible to manage variations with woocommerce_add_to_cart_valisation hook

相反,我们可以使用 Hook 在 woocommerce_add_to_cart 过滤器 Hook 中的自定义函数,当购物车中有超过 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 个属性值的购物车项目。

The only annoying thing is that I can't remove the classic added to cart notice for the moment. I will try to find another way…

关于php - 防止客户从 Woocommerce 中超过 3 个供应商处订购,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45594842/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com