Woocommerce 有你可以使用的验证钩子。
第一个是我们添加到购物车时
function add_to_cart_free_samples($valid, $product_id, $quantity) {
$max_allowed = 5;
$current_cart_count = WC()->cart->get_cart_contents_count();
foreach (WC()->cart->get_cart() as $cart_item_key=>$cart_item ){
// Here change attribute group if needed - currently assigned to default size attribute
$variation = $cart_item['variation']['attribute_pa_size'];
}
if( ( $current_cart_count > $max_allowed || $current_cart_count + $quantity > $max_allowed ) && $variation === 'free-sample' && $valid ){
wc_add_notice( sprintf( __( 'Whoa hold up. You can only have %d items in your cart', 'your-textdomain' ), $max_allowed ), 'error' );
$valid = false;
}
return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'add_to_cart_free_samples', 10, 3 );
第二个是当我们更新购物车页面上的购物车时。
function update_add_to_cart_free_samples( $passed, $cart_item_key, $values, $updated_quantity ) {
$cart_items_count = WC()->cart->get_cart_contents_count();
$original_quantity = $values['quantity'];
$max_allowed = 5;
$total_count = $cart_items_count - $original_quantity + $updated_quantity;
foreach (WC()->cart->get_cart() as $cart_item_key=>$cart_item ){
// Here change attribute group if needed - currently assigned to default size attribute
$variation = $cart_item['variation']['attribute_pa_size'];
}
if( $cart_items_count > $max_allowed && $variation === 'free-sample' ){
$passed = false;
wc_add_notice( sprintf( __( 'Whoa hold up. You can only have %d items in your cart', 'your-textdomain' ), $max_allowed ), 'error' );
}
return $passed;
}
add_filter( 'woocommerce_update_cart_validation', 'update_add_to_cart_free_samples', 10, 4 );
在 $cart_item 中,您可以调试并查看购物车中当前产品的所有信息。从那里您可以根据运输或属性或价格或您想要的 w/e 添加条件。