问题描述
我正在尝试为三种可变产品(464、465和466)设置特定的折扣.如果客户购买十种产品,他们将免费获得一种.
I'm trying to set up a specific discount for three variable products (464, 465 and 466). If a customer buys ten products they get one for free.
基于 WooCommerce折扣:买一送一50%的折扣答案代码,我想出了以下代码:
Based on WooCommerce discount: buy one get one 50% off answer code, I've come up with the following code:
add_action('woocommerce_cart_calculate_fees', 'add_custom_discount_11th_at_100', 10, 1 );
function add_custom_discount_11th_at_100( $wc_cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$discount = 0;
$items_prices = array();
// Set HERE your targeted variable product ID
$targeted_product_id = 464;
foreach ( $wc_cart->get_cart() as $key => $cart_item ) {
if( $cart_item['product_id'] == $targeted_product_id ){
$qty = intval( $cart_item['quantity'] );
for( $i = 0; $i < $qty; $i++ )
$items_prices[] = floatval( $cart_item['data']->get_price());
}
}
$count_items_prices = count($items_prices);
if( $count_items_prices > 10 ) foreach( $items_prices as $key => $price )
if( $key % 11 == 1 ) $discount -= number_format($price / 1, 11 );
if( $discount != 0 ){
// Displaying a custom notice (optional)
wc_clear_notices();
wc_add_notice( __("Buy 10 Get 1 Free"), 'notice');
// The discount
$wc_cart->add_fee( 'Buy 10 Get 1 Free', $discount, true );
# Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
}
但是它仅适用于一个产品ID.如何扩展它以适用于三个产品ID?
But it only works for one product ID. How do I expand it to work for three product Ids?
推荐答案
要使其适用于多种产品,您可以使用 in_array()
php函数,如下所示:
To make it work for multiple products you could use in_array()
php function as follow:
add_action('woocommerce_cart_calculate_fees', 'buy_ten_get_one_free', 10, 1 );
function buy_ten_get_one_free( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// Set HERE your targeted variable products IDs
$targeted_product_ids = array( 464, 465, 466 );
$each_n_items = 10; // Number of items required to get a free one
$discount = 0; // Initializing
$items_prices = array(); // Initializing
foreach ( $cart->get_cart() as $cart_item ) {
if( in_array( $cart_item['product_id'], $targeted_product_ids ) ) {
$qty = intval( $cart_item['quantity'] );
for ( $i = 0; $i < $qty; $i++ ) {
$items_prices[] = floatval( $cart_item['data']->get_price() );
}
}
}
$count_items_prices = count($items_prices);
if ( $count_items_prices > $each_n_items ) {
foreach ( $items_prices as $key => $price ) {
if ( $key % ($each_n_items + 1) == 1 ) {
$discount += number_format($price, 2 );
}
}
}
if ( $discount > 0 ) {
// Displaying a custom notice (optional)
wc_clear_notices();
wc_add_notice( __("Buy 10 Get 1 Free"), 'notice');
// The discount
$cart->add_fee( __("Buy 10 Get 1 Free"), -$discount, true );
}
}
代码进入您的活动子主题(或活动主题)的function.php文件中,已经过测试并且可以正常工作.
Code goes in function.php file of your active child theme (or active theme), tested and works.
这篇关于WooCommerce促销折扣:买10送1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!