我目前有一位销售线标涂料的客户,他们希望在其网站上提供按以下方式提供的报价:
如果顾客购买10种以上油漆(他们可以混合搭配),他们将免费获得3种,但只有最便宜的3种,免费...
示例如下:
我正在努力在 WooCommerce 中实现这一目标,尽管尝试的时间比我愿意承认的要长!!!
我希望以上是有道理的!
任何帮助或指导将不胜感激!
编辑:
我到目前为止的代码如下。它按顺序返回购物车中一系列最便宜的产品及其数量。问题是我只需要将折扣应用于 3 个产品,因此如果数组中的第一个产品的数量只有 2,我还需要将其应用于第二便宜的产品......依此类推......
function get_cheapest_x_products_in_cart($cat_id)
{
global $woocommerce;
$cat_products = [];
$cheapest_products;
// Add all cart items with correct category to array ($cat_products)
foreach( WC()->cart->get_cart() as $cart_item ) {
if( has_term( $cat_id, 'product_cat', $cart_item['product_id'])) {
$product = wc_get_product( $cart_item['product_id'] );
$price = $product->get_regular_price();
$cat_products[
$cart_item['product_id'] ] = [
'price' => floatval($price),
'quantity' => $cart_item['quantity'],
];
}
}
uasort($cat_products, "sort_this");
$cheapest_three_products = array_slice($cat_products, 0, 3, true);
return $cheapest_three_products;
}
在此自定义函数中,挂钩于
woocommerce_cart_calculate_fees
操作挂钩,客户将根据购物车中每 10 件商品的最便宜 3 件商品价格的总和获得折扣。
您必须定义产品类别,并且可以选择在应用折扣时收到自定义通知……
这是代码:
add_action( 'woocommerce_cart_calculate_fees', 'free_cheapest_3_each_10_items', 10, 1 );
function free_cheapest_3_each_10_items( $wc_cart ) {
if ( is_admin() && ! defined('DOING_AJAX') ) return;
// HERE define your product category (or categories) in the array (IDs slugs or names)
$cat_id = array('paints');
$prices = array();
$cat_id = array('clothing');
$discount = $items_count = 0;
foreach ( $wc_cart->get_cart() as $cart_item ){
$sale_price = $cart_item['data']->get_sale_price();
// Only for the defined product category(ies) and no items in sale
if( has_term( $cat_id, 'product_cat', $cart_item['product_id']) && ( empty($sale_price) || $sale_price == 0 ) ) {
for( $i = 0; $i < $cart_item['quantity']; $i++){
$prices[] = floatval( $cart_item['data']->get_regular_price() );
$items_count++;
}
}
}
if( $items_count >= 10 ){
// Ordering prices
asort($prices);
// Get the occurence number for 3 free items each 10 items
for( $i = 0, $j = -1; $i < $items_count; $i++ )
if( $i % 10 == 0 ) $j++;
$count = $j*3;
// Get the 3 free items for each 10 items in cart (for the defined product category(ies))
$free_cheapest_items = array_slice($prices, 0, $count, true);
// Calculate the discount amount
foreach( $free_cheapest_items as $item_price )
$discount -= $item_price;
// The discount
if( $discount != 0 ){
$wc_cart->add_fee( "Bulk discount", $discount, true );
// Displaying a custom notice (optional)
wc_clear_notices();
wc_add_notice( __("You get $count free items for the $items_count items in cart"), 'notice');
}
}
}
代码位于活动子主题(或主题)的 function.php 文件中,或者也位于任何插件文件中。
在 WooCommerce 3 上测试并有效。