【发布时间】:2021-08-09 10:43:19
【问题描述】:
我正在尝试在 WooCommerce 中实现以下目标。我想为特定产品设置最低订购量。
问题在于,例如该产品是可变产品,我想设置最少 12 件的数量,但我希望这个最小值出现在整个产品上,而不是每个变体上。
例如:
- 如果客户将 2 件该产品添加到购物车并选择 XL Black 的变体,则应有一个通知,最低数量为 12 件。
- 当该客户添加 10 件 L Red 相同产品的变体时,他已经满足了最低订单要求,他应该可以下订单了。
到目前为止,我的代码适用于简单的产品,但它会将变体视为不同的产品。
如何调整此设置,以便将购物车中的变体数量计为 1 件产品?
// Set minimum quantity per product before checking out
add_action( 'woocommerce_check_cart_items', 'spyr_set_min_qty_per_product' );
function spyr_set_min_qty_per_product() {
// Only run in the Cart or Checkout pages
if( is_cart() || is_checkout() ) {
global $woocommerce;
// Product Id and Min. Quantities per Product
$product_min_qty = array(
array( 'id' => 9059, 'min' => 12 ),
);
// Will increment
$i = 0;
// Will hold information about products that have not
// met the minimum order quantity
$bad_products = array();
// Loop through the products in the Cart
foreach( $woocommerce->cart->cart_contents as $product_in_cart ) {
// Loop through our minimum order quantities per product
foreach( $product_min_qty as $product_to_test ) {
// If we can match the product ID to the ID set on the minimum required array
if( $product_to_test['id'] == $product_in_cart['product_id'] ) {
// If the quantity required is less than than the quantity in the cart now
if( $product_in_cart['quantity'] < $product_to_test['min'] ) {
// Get the product ID
$bad_products[$i]['id'] = $product_in_cart['product_id'];
// Get the Product quantity already in the cart for this product
$bad_products[$i]['in_cart'] = $product_in_cart['quantity'];
// Get the minimum required for this product
$bad_products[$i]['min_req'] = $product_to_test['min'];
}
}
}
// Increment $i
$i++;
}
// Time to build our error message to inform the customer
// About the minimum quantity per order.
if( is_array( $bad_products) && count( $bad_products ) > 0 ) {
// Lets begin building our message
$message = '<strong>A minimum quantity per product has not been met.</strong><br />';
foreach( $bad_products as $bad_product ) {
// Append to the current message
$message .= get_the_title( $bad_product['id'] ) .' requires a minimum quantity of '
. $bad_product['min_req']
.'. You currently have: '. $bad_product['in_cart'] .'.<br />';
}
wc_add_notice( $message, 'error' );
}
}
}
【问题讨论】:
标签: php wordpress woocommerce product cart