我在WooCommerce商店卖手绘艺术品。由于它是手绘艺术品,所以产品数量限制在1件(每件订单限购1件)。
我已经为艺术品框架创造了以下产品变体:
变式1:木架(库存数量=1)变化2:丙烯酸框架(库存数量=1变体)
我想把订单限制在每种产品/每种变化的基础上。
用户只可以用木制或丙烯酸框架购买艺术品。
目前,用户可以添加到手推车艺术品与木和丙烯酸框架。
我不想让用户购买一个独特的手工制作的艺术品与两个不同的变化。
我怎样才能做到这一点?有什么函数可以用来限制这一点吗?
发布于 2022-11-21 10:10:25
请检查以下全球代码:
add_filter( 'woocommerce_add_to_cart_validation', 'allowed_products_variation_in_the_cart', 10, 5 );
function allowed_products_variation_in_the_cart( $passed, $product_id, $quantity, $variation_id, $variations) {
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
if($cart_item['product_id'] == $product_id)
{
wc_add_notice(__('You can\'t add this product.', 'domain'), 'error');
$passed = false; // don't add the new product to the cart
// We stop the loop
break;
}
}
return $passed;
}此外,如果您必须为某些产品制作,那么您可以在产品中创建一个自定义字段并启用它。然后在前面使用自定义代码,然后在购物车验证中进行验证,它将在您定义的产品中执行。。
如果你发现任何问题请告诉我。
发布于 2022-11-21 12:01:35
这是对我有用的代码。
add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_custom_add_to_cart_validation', 10, 5 );
function woocommerce_custom_add_to_cart_validation ($passed, $product_id, $quantity, $variation_id, $variations) {
$variation_id_to_delete = null;
$is_current_variation = false;
foreach ( WC()->cart->get_cart() as $item_key => $item ) {
$product = $item['data'];
$attributes = $product->get_attributes();
if($variations['attribute_varient-id'] == $product->get_attribute('varient-id')) { // IMPORTANT = ATTRIBUTE NAMES SHOULD MATCH WITH WC ATTRIBUTES
$variation_id_to_delete = $item_key;
$is_current_variation = true;
break;
}
}
// IF IS_CURRENT_VARIATION_ID : DELETE
if ($is_current_variation){
WC()->cart->remove_cart_item($variation_id_to_delete);
}
return $passed;
}https://stackoverflow.com/questions/74515613
复制相似问题