php - 如果未达到特定类别的最低数量,则阻止 WooCommerce 结帐
问题描述
我有一些购物车逻辑,如果冷藏类别中的1 件商品在购物车中,它会检查至少 3 件商品。- 这是经过测试和工作的。
但是,如果我从不同的类别 ( ambient )将另一个物品添加到购物车,并且购物车中现在既有冷藏物品,也有环境物品,则不再应用该规则。
如果购物车中也有环境物品,我如何确保应用 3 冷藏最低规则?
// Set minimum quantity per product before checking out
add_action( 'woocommerce_check_cart_items', 'protein_set_min_total' );
function protein_set_min_total() {
// Only run in the Cart or Checkout pages
if( is_cart() || is_checkout() ) {
global $woocommerce, $product;
$i=0;
// Set minimum product cart total
//And initialise product catergory counters
$minimum_protein = 3;
$total_protein = 0;
$cat_in_cart = false;
foreach ( $woocommerce->cart->cart_contents as $product ) :
if ( has_term( 'chilled', 'product_cat', $product['product_id'] ) ) {
$total_protein += $product['quantity'];
}
endforeach;
if (has_term( 'chilled', 'product_cat', $product['product_id'] ) && $total_protein < $minimum_protein) {
wc_add_notice( sprintf( '<strong>A Minimum of %s products are required from The CHILLED category before checking out.</strong>'
. '<br />Current number of Chilled items in the cart: %s.',
$minimum_protein,
$total_protein ),
'error' );
}
//}
}
}
解决方案
下面的代码将计算属于该chilled
类别的所有项目。只有当这等于或大于 3 时,才有可能继续订购过程。
所以你得到:
function action_woocommerce_check_cart_items() {
// Only run on the cart or checkout pages
if ( is_cart() || is_checkout() ) {
// Minimum
$minimum = 3;
// Category
$category = 'chilled';
// Initialize
$total = 0;
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// Product id
$product_id = $cart_item['product_id'];
// Has certain category
if ( has_term( $category, 'product_cat', $product_id ) ) {
// Add to total
$total += $cart_item['quantity'];
}
}
// When total is greater than 0 but less than the minimum
if ( $total > 0 && $total < $minimum ) {
// Notice
wc_add_notice( sprintf( __( 'A minimum of %s products are required from the %s category before checking out.', 'woocommerce' ), $minimum, $category ), 'error' );
// Optional: remove proceed to checkout button
remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
}
}
}
add_action( 'woocommerce_check_cart_items' , 'action_woocommerce_check_cart_items', 10, 0 );
推荐阅读
- javascript - 在 `Then` 中调用相同的承诺
- office-js - 限制 Office 应用中基于表单的身份验证
- laravel - Laravel:条件验证规则
- scala - 如何防止“scalike”将“LocalDateTime”转换为特定的 LocalDateTime
- python-3.x - 如何在本地而不是在主机上从 Web 应用程序运行功能
- bixby - Bixby 运行时版本 3
- regex - 我正在尝试使用正则表达式来提取在 Splunk 中归档的文件名,我附上了相同的文本
- java - Java 客户端服务器菜单
- scala - 如何将日期格式“dd-MMM-yy”的字符串转换为DateType
- mqtt - 告诉 moquitto 服务器/经纪人保留某些主题?