在最便宜的产品上每3种产品增加50%的折扣(WooCommerce)

本教程将介绍在最便宜的产品上每3种产品增加50%的折扣(WooCommerce)的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

在最便宜的产品上每3种产品增加50%的折扣(WooCommerce) 教程 第1张

问题描述

我为每3个产品添加折扣规则:3、6、9、12、15。在购物车上,它应该只适用于最便宜的产品50%的折扣。

因此,如果您有9个,只有最便宜的3个才能享受50%的折扣。

此代码将折扣应用于所有产品,因此它应该只适用于每3个产品

add_action('woocommerce_cart_calculate_fees', 'ts_add_custom_discount', 10, 1 );
function ts_add_custom_discount( $wc_cart ){
 $discount = 0;
 $product_ids = array();
 $item_prices = array();
 $in_cart = false;

 foreach ( $wc_cart->get_cart() as $cart_item_key => $cart_item ) {
  $cart_product = $cart_item['data'];
  if ( has_term( 'get2', 'product_cat', $cart_product->get_id() ) ) { // get2 selected category
$in_cart = true;
  }else {
$in_cart = true;
$product_ids[] = $cart_product->get_id();
$item_prices[$cart_product->get_id()] = $cart_product->get_price();
  }
 }

 if( $in_cart ) {

  $count_ids = count($product_ids);

  asort( $item_prices ); //Sort the prices from lowest to highest

  $cartQuantity = WC()->cart->cart_contents_count;

  $count = 0;

  if( $count_ids > 3 || $cartQuantity >= 3 ) { 
  foreach( $item_prices as $id => $price ) {
 if( $count >= 1 ) {
  break;
 }
 //$product = wc_get_product( $id );
 //$price = $product->get_price();
 $discount -= ($price * 50) /100;
 $count++;
  }
 }

 } 

 if( $discount != 0 ){
  $wc_cart->add_fee( 'Discount', $discount, true  );
 }
}

我已经附上了screenshot,您可以看到每个第三便宜的产品都有一个红色轮廓。

推荐答案

此代码将对最便宜的产品每3个产品应用50%的折扣。

function custom_fee( $cart ) {
 if ( is_admin() && ! defined( 'DOING_AJAX' ) )
  return;

 // Products in cart
 $products_in_cart = count( $cart->get_cart() );

 // Every so many products
 $every = 3;

 // When products in cart greater than or equal to every so many products
 if ( $products_in_cart >= $every ) {
  // Set array
  $product_prices = array();

  // Loop though cart items
  foreach ( $cart->get_cart() as $cart_item ) {
// Product
$product = $cart_item['data'];

// Get price
$product_price = $product->get_price();

// Push
$product_prices[] = $product_price;
  }

  // Sort: low to high
  asort( $product_prices );

  // Number of products receive a discount
  $products_receive_discount = floor( $products_in_cart / $every );

  // Set variable
  $total = 0;

  // Loop trough
  foreach ( array_slice( $product_prices, 0, $products_receive_discount ) as $product_price ) {
// Calculate
$total += $product_price;
  }

  // Calculate discount
  $discount = ( $total * 50 ) / 100;

  // Add fee
  $cart->add_fee( 'Discount', $discount, true );
 }
}
add_action( 'woocommerce_cart_calculate_fees', 'custom_fee', 10, 1 );

好了关于在最便宜的产品上每3种产品增加50%的折扣(WooCommerce)的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。