我已经寻找这个问题很长时间了,但似乎从未找到可能的解决方案。
有谁看到任何解决方案如何在一个 Woocommerce 购物车中仅允许物理或虚拟产品?当客户尝试添加虚拟和物理的组合并禁止该组合时,或者确保该组合不能出现在一个购物车中时,可能会弹出通知。
按顺序进行组合会不断导致错误。
请帮忙。
以下将避免将购物车中的物理产品和虚拟产品组合在一起:
// Check cart items and avoid add to cart
add_filter( 'woocommerce_add_to_cart_validation', 'filter_wc_add_to_cart_validation', 10, 3 );
function filter_wc_add_to_cart_validation( $passed, $product_id, $quantity ) {
$is_virtual = $is_physical = false;
$product = wc_get_product( $product_id );
if( $product->is_virtual() ) {
$is_virtual = true;
} else {
$is_physical = true;
}
// Loop though cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
// Check for specific product categories
if ( ( $cart_item['data']->is_virtual() && $is_physical )
|| ( ! $cart_item['data']->is_virtual() && $is_virtual ) ) {
wc_add_notice( __( "You can't combine physical and virtual products together.", "woocommerce" ), 'error' );
return false;
}
}
return $passed;
}
// For security: check cart items and avoid checkout
add_action( 'woocommerce_check_cart_items', 'filter_wc_check_cart_items' );
function filter_wc_check_cart_items() {
$cart = WC()->cart;
$cart_items = $cart->get_cart();
$has_virtual = $has_physical = false;
// Loop though cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
// Check for specific product categories
if ( $cart_item['data']->is_virtual() ) {
$has_virtual = true;
} else {
$has_physical = true;
}
}
if ( $has_virtual && $has_physical ) {
// Display an error notice (and avoid checkout)
wc_add_notice( __( "You can't combine physical and virtual products together.", "woocommerce" ), 'error' );
}
}
代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)