我希望对特定可变产品设置特定折扣,但对于某些选定的变体而不是所有变体:
例如:我的变量 id - 1571
变体 ID - 1572
变体 ID - 1573
因此,如果客户购买一种产品,他们会以 50% 的折扣购买另一种(相同的)产品(买一件产品可享受 50% 的折扣)。
我尝试过很多折扣插件,我发现的最接近的是:
- Pricing Deals for WooCommerce,
- Conditional Discounts for WooCommerce
- WooCommerce Extended Coupon Features FREE
对于其中一些,我能够设置小计折扣或每种产品的折扣,但不完全是我想要的(买 1 送 1 折扣)。还有其他专业插件我不想使用。
我找到的最接近的代码是 WooCommerce discount: buy one get one 50% off with a notice 。
是否可以对可变产品的特定产品变体的第二件商品进行折扣(仅针对每个产品变体)?
- 麦
最佳答案
要在可变产品的某些特定产品变体的第二件商品上获得 50% 的折扣,您将使用以下内容:
add_action('woocommerce_cart_calculate_fees', 'add_custom_discount_2nd_at_50', 10, 1 );
function add_custom_discount_2nd_at_50( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// YOUR SETTINGS:
$product_variations_ids = array(1572, 1573); // <== HERE your targeted product variations
// Initializing variables
$discount = 0;
$product_names = array();
// Loop through cart items
foreach ( $cart->get_cart() as $key => $cart_item ) {
if ( in_array( $cart_item['variation_id'], $product_variations_ids ) ) {
$qty = (int) $cart_item['quantity'];
$price = (float) $cart_item['data']->get_price();
$name = (string) $cart_item['data']->get_name();
if ( $qty > 1 ) {
$discount -= number_format( $price / 2, 2 );
}
elseif( $qty = 1 ) {
$product_names[] = $name;
}
}
}
// Applying the discount
if( $discount != 0 ){
$cart->add_fee('Buy one get one 50% off', $discount );
}
// Display a custom reminder notice on cart page (otional)
if( ! empty($product_names) ){
wc_clear_notices(); // clear other notices on checkout page.
if( ! is_checkout() ){
wc_add_notice( sprintf(
__( "Add one more to get 50%% off on the 2nd item for %s" ),
'"<strong>' . implode(', ', $product_names) . '</strong>"'
), 'notice' );
}
}
}
代码位于事件子主题(或事件主题)的functions.php文件中,经过测试并有效。
要以每件购买商品 50% 的折扣购买一件商品,而不是第二件商品享受 50% 的折扣,请替换:
$discount -= number_format( $price / 2, 2 );
作者:
$multiplier = ( $qty % 2 ) === 0 ? $qty / 2 : ( $qty - 1 ) / 2;
$discount -= number_format( $price / 2 * $multiplier, 2 );
要获得第二件免费商品,而不是第二件商品的 50% 折扣,请替换代码行:
$discount -= number_format( $price / 2, 2 );
作者:
$discount -= $price;
要为购买的每件商品免费获得 1 件商品,而不是为第 2 件商品提供 50% 折扣,请替换:
$discount -= number_format( $price / 2, 2 );
作者:
$multiplier = ( $qty % 2 ) === 0 ? $qty / 2 : ( $qty - 1 ) / 2;
$discount -= $price * $multiplier;
关于wordpress - WooCommerce 产品变体买一送二可享受 50% 的折扣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61223671/