我希望更改功能validate_coupon_minimum_amount()
添加一个条件,即如果用户使用优惠券 "refresh18"
,请检查购物车中产品类别的小计是否大于优惠券的最低金额。
我怎么能这样做?
以下是我的代码无效:
function check_minimum_parts_amount_in_cart($coupon) {
$cart_parts_subtotal = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
$product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
$terms = get_the_terms( $product_id, 'product_cat' );
if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_cart_item_visible', true, $cart_item, $cart_item_key ) && has_term( 'ice-shaving-parts', 'product_cat', $product_id ) ) {
//echo '<pre>' . print_r($cart_item , 1) . '</pre>';
//echo $cart_item['quantity'];
$cart_parts_subtotal = $cart_parts_subtotal + ( $_product->get_price() * $cart_item['quantity'] );
}
}
$subtotal = wc_remove_number_precision( $this->get_object_subtotal() );
if( $coupon->get_name() == 'refresh2018' ){
if( $coupon->get_minimum_amount() > 0 && apply_filters( 'woocommerce_coupon_validate_minimum_amount', $coupon->get_minimum_amount() > $cart_parts_subtotal, $coupon, $cart_parts_subtotal )){
/* translators: %s: coupon minimum amount */
throw new Exception( sprintf( __( 'The minimum spend for this coupon is %s.', 'woocommerce' ), wc_price( $coupon->get_minimum_amount() ) ), 108 );
}else{
return true;
}
}else{
if ( $coupon->get_minimum_amount() > 0 && apply_filters( 'woocommerce_coupon_validate_minimum_amount', $coupon->get_minimum_amount() > $subtotal, $coupon, $subtotal )) {
/* translators: %s: coupon minimum amount */
throw new Exception( sprintf( __( 'The minimum spend for this coupon is %s.', 'woocommerce' ), wc_price( $coupon->get_minimum_amount() ) ), 108 );
}else{
return true;
}
}
}
add_filter('validate_coupon_minimum_amount', 'check_minimum_parts_amount_in_cart');
答案 0 :(得分:1)
<强>更新强>
由于Woocommerce 3.2+使用 woocommerce_coupon_validate_minimum_amount
过滤器钩子...所以你应该尝试这个重新访问的代码(你必须在哪里设置你的产品类别):
add_filter( 'woocommerce_coupon_validate_minimum_amount', 'custom_check_minimum_amount_in_cart', 10, 3 );
function custom_check_minimum_amount_in_cart( $valid, $coupon, $subtotal ) {
// HERE below your settings (Coupon code and product category)
$coupon_code = 'refresh18';
$product_category = 'clothing'; // <== To be replaced by your targeted product category
$cat_subtotal = 0;
foreach ( WC()->cart->get_cart() as $cart_item ){
if( has_term( $product_category, 'product_cat', $cart_item['product_id'] ) )
$cat_subtotal += $cart_item['line_subtotal'];
}
if( $coupon->get_code() == $coupon_code && $coupon->get_minimum_amount() > $cat_subtotal ){
throw new Exception( sprintf( __( 'The minimum spend for this coupon is %s.', 'woocommerce' ), wc_price( $coupon->get_minimum_amount() ) ), 108 );
}
return $valid;
}
此代码位于您的活动子主题(或主题)的function.php文件中。它应该有效。
注意:对于每个人,请记住在此功能中设置小写的优惠券代码。