问题描述
我正尝试只允许特定类别(具有一些子类别)或最多4个子类别(coffee1,流行混合,订阅,chaiandchocolate)组合的订单,最高限额为$ 32。
基于Minimum cart amount for specific product categories in WooCommerce的答案代码,这是我的代码:
add_action( 'woocommerce_check_cart_items','check_cart_coffee_items' );
function check_cart_coffee_items() {
$categories = array('coffee'); // Defined targeted product categories
$threshold = 32; // Defined threshold amount
$cart = WC()->cart;
$cart_items = $cart->get_cart();
$subtotal = $cart->subtotal;
$subtotal -= $cart->get_cart_discount_total() + $cart->get_cart_discount_tax_total();
$found = false;
foreach( $cart_items as $cart_item_key => $cart_item ) {
// Check for specific product categories
if ( has_term( $categories,'product_cat',$cart_item['product_id'] ) ) {
$found = true; // A category is found
break; // Stop the loop
}
}
if ( $found && $subtotal < $threshold ) {
// Display an error notice (and avoid checkout)
wc_add_notice( sprintf( __( "You must order at least %s of coffee" ),wc_price($threshold) ),'error' );
}
}
但是我无法使它适用于整个咖啡类别或任何单个子类别。欢迎提供帮助。
解决方法
请尝试以下操作,它将检查“咖啡”主类别的所有子类别中的项目(以及包括该子类别中的税款在内的非折扣小计):
add_action( 'woocommerce_check_cart_items','minimum_order_amount_for_subcategories' );
function minimum_order_amount_for_subcategories() {
$term_slug = 'coffee'; // <== Define the targeted main product category slug
$threshold = 32; // <== Define the minimum amount threshold
$taxonomy = 'product_cat'; // WooCommerce product category taxonomy
$subtotal = 0; // Itintializing
$found = false; // Itintializing
// Get the children terms Ids from the main product category term slug
$main_term = get_term_by( 'slug',$term_slug,$taxonomy );
$childen_ids = get_term_children( $main_term->term_id,$taxonomy );
$terms_ids = array_merge( array($main_term->term_id),$childen_ids);
foreach( WC()->cart->get_cart() as $cart_item ) {
// Check for specific product category children term ids
if ( has_term( $terms_ids,$taxonomy,$cart_item['product_id'] ) ) {
$found = true; // At least subcategory is found
// Get non discounted subtotal including taxes from subcategories
$subtotal += $cart_item['line_subtotal'] + $cart_item['line_subtotal_tax'];
}
}
if ( $found && $subtotal < $threshold ) {
// Display an error notice (and avoid checkout)
wc_add_notice( sprintf(
__( "You must order at least %s of %s","woocommerce" ),wc_price($threshold),'"<strong>' . ucfirst($term_slug) . '</strong>"'
),'error' );
}
}
代码进入活动子主题(或活动主题)的functions.php文件中。应该可以。