【发布时间】:2021-05-08 13:00:27
【问题描述】:
我需要为 WooCommerce 中的某些类别强制设置最低订单金额,因此在购物车和结帐页面中设置警报。
到目前为止,如果购物车中的总金额低于设置的最低金额,我设法设置了警报,但我无法创建基于类别的过滤器。实际上,购物车中添加了任何其他产品,警报已被超越,并且允许用户购买我想要限制的该类别的产品。
代码如下:
/**
* Set a minimum order amount for checkout
*/
add_action( 'woocommerce_checkout_process', 'wc_minimum_order_amount' );
add_action( 'woocommerce_before_cart' , 'wc_minimum_order_amount' );
add_action( 'woocommerce_before_checkout' , 'wc_minimum_order_amount' );
function wc_minimum_order_amount() {
// Set this variable to specify a minimum order value
$minimum = 30;
// set array with cat IDs
$category_ids = array( 336, 427, 433 );
// set bool that checks is minimum amount has been reached
$needs_minimum_amount = false; // Initializing
$subTotal_amount = WC()->cart->subtotal; // Items subtotal including taxes
$total_amount = WC()->cart->total; // Items subtotal excluding taxes
if ( $total_amount < $minimum ) {
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
$product_id = $cart_item['product_id'];
$variation_id = $cart_item['variation_id'];
// Check for matching product categories
if( sizeof($category_ids) > 0 ) {
$taxonomy = 'product_cat';
if ( has_term( $category_ids, $taxonomy, $product_id ) ) {
$needs_minimum_amount = true;
break; // Stop the loop
}
}
}
if( $needs_minimum_amount ) {
if( is_cart()) {
wc_print_notice(
sprintf( 'Your current order total is %s — you must have an order with a minimum of %s to place your order ' ,
wc_price( WC()->cart->total ),
wc_price( $minimum )
), 'error'
);
} else {
wc_add_notice(
sprintf( 'Your current order total is %s — you must have an order with a minimum of %s to place your order' ,
wc_price( WC()->cart->total ),
wc_price( $minimum )
), 'error'
);
}
}
}
}
参考资料:
- Set minimum Order amount for specific Products or Categories in WooCommerce
- https://docs.woocommerce.com/document/minimum-order-amount/
有什么帮助吗?
【问题讨论】:
标签: php wordpress woocommerce cart checkout