【发布时间】:2020-11-15 20:46:07
【问题描述】:
我需要一些帮助来将自定义运费与 WooCommerce 中的购物车商品折扣价格结合起来。
在下面的代码中,第一个函数负责根据所选的交付选项添加 50% 的折扣,并且 第二个负责计算购物篮中每件商品的 50% 折扣,特定类别(及其子类别)除外。
我想确保当客户选择“自提”送货时显示“-50%”的折扣,该折扣仅适用于未包含在特定类别及其子类别中的商品(对于主要类别 ID 37).
第一个函数:
add_filter('woocommerce_package_rates', 'local_pickup_percentage_discount', 12, 2);
function local_pickup_percentage_discount( $rates, $package ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
// HERE define the discount percentage
$percentage = 50; // 50%
$subtotal = WC()->cart->get_subtotal();
// Loop through the shipping taxes array
foreach ( $rates as $rate_key => $rate ){
$has_taxes = false;
// Targeting "Local pickup"
if( 'local_pickup' === $rate->method_id ){
// Add the Percentage to the label name (optional
$rates[$rate_key]->label .= ' ( - ' . $percentage . '% )';
// Get the initial cost
$initial_cost = $new_cost = $rates[$rate_key]->cost;
// Calculate new cost
$new_cost = -$subtotal * $percentage / 100;
// Set the new cost
$rates[$rate_key]->cost = $new_cost;
// Taxes rate cost (if enabled)
$taxes = [];
// Loop through the shipping taxes array (as they can be many)
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $rates[$rate_key]->taxes[$key] > 0 ){
// Get the initial tax cost
$initial_tax_cost = $new_tax_cost = $rates[$rate_key]->taxes[$key];
// Get the tax rate conversion
$tax_rate = $initial_tax_cost / $initial_cost;
// Set the new tax cost
$taxes[$key] = $new_cost * $tax_rate;
$has_taxes = true; // Enabling tax
}
}
if( $has_taxes )
$rates[$rate_key]->taxes = $taxes;
}
}
return $rates;
}
第二个:
add_action( 'woocommerce_before_calculate_totals', 'custom_cart_item_price', 10, 1 );
function custom_cart_item_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$parent_id = 37; // premium-rolls id
$taxonomy = 'product_cat';
foreach ( $cart->get_cart() as $cart_item ){
$product_id = $cart_item['product_id'];
$terms_ids = get_term_children( $parent_id, $taxonomy, $product_id ); // get children terms ids array
array_unshift( $terms_ids, $parent_id ); // insert parent term id to children terms ids array
if ( ! has_term( $terms_ids, $taxonomy, $product_id ) ){
$new_price = $cart_item['data']->get_price() / 2; // Get 50% of the initial product price
$cart_item['data']->set_price( $new_price ); // Set the new price
}
}
}
【问题讨论】:
-
您想在哪里准确显示“-50%”?您的问题不清楚......即使有来自不同类别的多个项目,包括类别 37(融化的项目),运输方式也适用于所有项目......
-
我想在“Local Pickup”旁边显示“(-50%)”,如果客户选择了“Local Pickup”,那么购物车中的所有商品的成本都会降低 50%,除了特定类别的商品
-
@LoicTheAztec,如果我理解正确的话,这是不可能的,对吧?
-
我想我已经找到了让它像您在下面的答案中所期望的那样工作的方法。
标签: php jquery wordpress woocommerce price