php - 基于产品 ID 的 WooCommerce 批量折扣
问题描述
我正在尝试在 WooCommerce 中设置批量折扣。
现在,我有这个
function se_bulkdiscount_on_ids( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// Set special prices
$special_price = array(
2 => '1.2',
3 => '1.3',
4 => '1.4',
5 => '1.5',
6 => '1.6',
7 => '1.7',
8 => '1.8',
);
// Set product ids
$specific_product_ids = array( 1465, 1785 );
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Get product id
$product_id = $cart_item['product_id'];
// Compare
if ( in_array( $product_id, $specific_product_ids ) ) {
foreach($special_price as $quantity => $price){
if($cart_item['quantity'] >= $quantity){
$cart_item['data']->set_price( $price );
}
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'se_bulkdiscount_on_ids', 10, 1 );
但是,我如何才能仅针对特定产品 ID 设置此折扣?
如果我有 ID 1300 1x 和 1403 2x 这有 3 个数量一起比价格是每件 1.62
解决方案
假设你是这个意思?注释并在代码中添加解释
function se_bulkdiscount_on_ids( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
/* SETTINGS */
// Set special prices
$special_price = array(
1 => 1.1,
2 => 1.2,
3 => 1.3,
4 => 1.4,
5 => 1.5,
6 => 1.6,
7 => 1.7,
8 => 1.8,
);
// Set product ids
$specific_product_ids = array( 30, 813 );
/* END SETTINGS */
// total items
$count = 0;
// Loop through cart items (count)
foreach ( $cart->get_cart() as $cart_item ) {
// Get product id
$product_id = $cart_item['product_id'];
// Quantity
$product_quantity = $cart_item['quantity'];
// Compare
if ( in_array( $product_id, $specific_product_ids ) ) {
$count += $product_quantity;
}
}
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Get product id
$product_id = $cart_item['product_id'];
// Compare
if ( in_array( $product_id, $specific_product_ids ) ) {
// If count is in range of the array
if ( $count >= 2 & $count <= count( $special_price ) ) {
// set new price
$cart_item['data']->set_price( $special_price[$count] );
} elseif ( $count > count( $special_price ) ) {
// set new price
$cart_item['data']->set_price( end($special_price) );
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'se_bulkdiscount_on_ids', 10, 1 );
推荐阅读
- javascript - 如何将 geocoder.geocode() 中的地址存储在 GeocoderService 中并将其返回给 app.component?
- c# - 在 C# 程序中使用枚举内部属性来增加投票计数器
- visual-studio-2017 - 如何清洁包括 nuget 包
- math - 使用 C# 传递变量时求解此等式中的“x”
- colors - IOS中分段控制的背景颜色
- mysql - 无法删除触发器,因为它“不存在”
- java - 使用 HQL(休眠查询语言)转换查询 Oracle
- c# - c#中具有多个类型参数的泛型方法
- node.js - 使用 azure-mobile-apps 和 NodeJS 创建子连接
- xml - 如何从 OpenAPI 3.0 规范生成 XSD 文件?