我正在尝试为所有带有标签的产品添加动态折扣:“批量折扣”我希望如果客户购买例如,则折扣会发生。带有标签的5个相似或不同的产品。
我正在使用this代码。还有this的答案。 这就是我所拥有的:
add_action( 'woocommerce_before_calculate_totals', 'bbloomer_quantity_based_pricing', 9999 );
function bbloomer_quantity_based_pricing( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Get an instance of the WC_Product object
$product = $cart_item['data'];
// Get product id
$product_id = $cart_item['product_id'];
if( method_exists( $product, 'set_name' ) && has_term( 'bulk-discount', 'product_tag', $product_id ) ) {
// Define discount rules and thresholds
$threshold1 = 5; // Change price if items > 4
$discount1 = 0.05; // Reduce unit price by 5%
$threshold2 = 10; // Change price if items > 9
$discount2 = 0.1; // Reduce unit price by 10%
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item['quantity'] >= $threshold1 && $cart_item['quantity'] < $threshold2 ) {
$price = round( $cart_item['data']->get_price() * ( 1 - $discount1 ), 2 );
$cart_item['data']->set_price( $price );
} elseif ( $cart_item['quantity'] >= $threshold2 ) {
$price = round( $cart_item['data']->get_price() * ( 1 - $discount2 ), 2 );
$cart_item['data']->set_price( $price );
}
}
}
答案 0 :(得分:2)
我想你是这个意思?
第一个循环计算标签在一个产品或同一产品中的多个产品上出现的次数
如果满足条件,则第二个循环应用折扣
function bbloomer_quantity_based_pricing( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
// count tag found
$tag_found = 0;
// Loop through cart items, count how many times tag occurs
foreach ( $cart->get_cart() as $cart_item ) {
// Get an instance of the WC_Product object
$product = $cart_item['data'];
// Get product id
$product_id = $cart_item['product_id'];
// if product has tag
if( has_term( 'bulk-discount', 'product_tag', $product_id ) ) {
// Get quantity from product in cart
$quantity = $cart_item['quantity'];
// if product quantity > 1
if ( $quantity > 1) {
$tag_found = $tag_found + $quantity;
} else {
$tag_found += 1;
}
}
}
// Define discount rules and thresholds
$threshold = 5; // Change price if items > 4
$discount = 0.05; // Reduce unit price by 5%
// if tag found >= $threshold
if ( $tag_found >= $threshold ) {
// Loop through cart items, add discount
foreach ( $cart->get_cart() as $cart_item ) {
// Get an instance of the WC_Product object
$product = $cart_item['data'];
// Get product id
$product_id = $cart_item['product_id'];
// if product has tag
if( has_term( 'bulk-discount', 'product_tag', $product_id ) ) {
// calculate new price
$price = round( $cart_item['data']->get_price() * ( 1 - $discount ), 2 );
// set new price
$cart_item['data']->set_price( $price );
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'bbloomer_quantity_based_pricing', 10, 1 );