当他们在WooCommerce中购买x数量的特定产品类别时,根据用户角色应用折扣 [英] Apply discount based on user role when they buy x quantity of specific product category in WooCommerce
本文介绍了当他们在WooCommerce中购买x数量的特定产品类别时,根据用户角色应用折扣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为我的基于客户的用户角色打折,例如:
- 对于用户角色(订阅者),如果他们购买特定类别的25个产品,则可享受50%的折扣。
如果使用了代码片段,但它没有涵盖我问题的第二部分(来自特定类别的25种产品)。
// Applying conditionally a discount for a specific user role
add_action( 'woocommerce_cart_calculate_fees', 'discount_on_user_role', 20, 1 );
function discount_on_user_role( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return; // Exit
// Only for 'company' user role
if ( ! current_user_can('company') )
return; // Exit
// HERE define the percentage discount
$percentage = 50;
$discount = $cart->get_subtotal() * $percentage / 100; // Calculation
// Applying discount
$cart->add_fee( sprintf( __("Discount (%s)", "woocommerce"), $percentage . '%'), -$discount, true );
}
有什么建议吗?
推荐答案
对于类别categorie-1
(根据需要进行调整),您可以根据购物车中的产品数量使用计数器。
当此值等于或大于25时,您可以应用折扣。
因此您得到:
function action_woocommerce_cart_calculate_fees( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Only for 'company' user role
if ( ! current_user_can( 'company' ) )
return;
// Category
$category = 'categorie-1';
// Percentage discount
$percentage = 50; // 50%
// Min quantity
$minimun_quantity = 25;
// Initialize
$current_quantity = 0;
$current_total = 0;
// Loop though each cart item
foreach ( $cart->get_cart() as $cart_item ) {
// Has certain category
if ( has_term( $category, 'product_cat', $cart_item['product_id'] ) ) {
// Get quantity
$product_quantity = $cart_item['quantity'];
// Add to quantity total
$current_quantity += $product_quantity;
// Get price
$product_price = $cart_item['data']->get_price();
// Add to current total
$current_total += $product_price * $product_quantity;
}
}
// Greater than or equal to
if ( $current_quantity >= $minimun_quantity ) {
// Calculation
$discount = $current_total * $percentage / 100;
// Applying discount
$cart->add_fee( sprintf( __( 'Discount (%s)', 'woocommerce' ), $percentage . '%'), -$discount, true );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
这篇关于当他们在WooCommerce中购买x数量的特定产品类别时,根据用户角色应用折扣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文