问题
I have a category of products that are all priced at $15. When the user buys between 10 & 20 products from this category they should receive a discounted price of $10. When the user buys 20+ the price changes again to $5. The user cannot have a custom role assigned to them (like wholesaler). I created code loosely based on LoicTheAztec code from another question and added my own modifications and code. It looks like it should work. I receive no errors but it does not work.
add_action('woocommerce_before_cart', 'check_product_category_in_cart');
function check_product_category_in_cart() {
// HERE set your product categories in the array (can be IDs, slugs or names)
$categories = array('surfacing-adhesives');
$found = false; // Initializing
$count = 0;
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
// If product categories is found
if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
$count++;
}
}
if (!current_user_can('wholesaler')) {
// Discounts
if ($count > 10 && $count < 20) {
// Drop the per item price
$price = 10;
} else if ($count > 20) {
// Drop the per item price
$price = 5;
} else {
// Did not qualify for volume discount
}
}
}
回答1:
You are not using the correct hook and there are some missing things. Try the following:
add_action( 'woocommerce_before_calculate_totals', 'discounted_cart_item_price', 20, 1 );
function discounted_cart_item_price( $cart ){
// Not for wholesaler user role
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || current_user_can('wholesaler') )
return;
// Required since Woocommerce version 3.2 for cart items properties changes
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// HERE set your product categories in the array (can be IDs, slugs or names)
$categories = array('surfacing-adhesives');
$categories = array('t-shirts');
// Initializing
$found = false;
$count = 0;
// 1st Loop: get category items count
foreach ( WC()->cart->get_cart() as $cart_item ) {
// If product categories is found
if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
$count += $cart_item['quantity'];
}
}
// Applying discount
if ( $count >= 10 ) {
// Discount calculation (Drop the per item qty price)
$price = $count >= 20 ? 5 : 10;
// 2nd Loop: Set discounted price
foreach ( WC()->cart->get_cart() as $cart_item ) {
// If product categories is found
if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
$cart_item['data']->set_price( $price );
}
}
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
来源:https://stackoverflow.com/questions/62440317/discount-based-on-item-quantity-count-for-a-category-in-woocommerce-cart