这是代码
add_filter( 'woocommerce_add_to_cart_validation', 'only_one_product_type_allowed', 10, 3 );
function only_one_product_type_allowed( $passed, $product_id, $quantity ) {
$product = wc_get_product( $product_id );
$product_type = $product->get_type();
$product_downloadable = $product->is_downloadable();
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( $product_type == $cart_item['data']->get_type() && $product_downloadable == $cart_item['data']->is_downloadable() && ! $product->is_virtual() ) {
wc_add_notice( __( "NOTICE ON CART PAGE.", "woocommerce" ), 'error' );
return false;
}
}
return $passed;
}
现在,单个购物车中不允许有多个可下载产品,这是可以的。但购物车中也不允许有超过一件常规商品。它发出了同样的通知。任何人都可以帮忙修复吗?
要在购物车中仅允许一种可下载产品,而允许其他产品种类,请尝试使用以下内容:
add_filter( 'woocommerce_add_to_cart_validation', 'only_one_downloadable_product_allowed', 10, 4 );
function only_one_downloadable_product_allowed( $passed, $product_id, $quantity, $variation_id = null ) {
// Get the current product object
$product = wc_get_product( $variation_id > 0 ? $variation_id : $product_id );
// Initializing downloadable product count
$count_dl = $product->is_downloadable() ? 1 : 0;
// Loop through cart items
foreach ( WC()->cart->get_cart() as $item ) {
// Check for downloadable products in cart
if ( $item['data']->is_downloadable() ) {
$count_dl++;
}
}
if ( $count_dl > 1 ) {
wc_add_notice( __( "Only one downloadable product is allowed at the time.", "woocommerce" ), 'error' );
$passed = false;
}
return $passed;
}
代码位于子主题的functions.php 文件中(或插件中)。应该可以。