問題描述
我有一個 woocommerce 商店,有 3 個用戶角色,我想僅為用戶角色公司"提供購物車總額 10% 的折扣.
I have a woocommerce store, with 3 user roles, I want to provide a 10% discount on the cart total only for a user role 'company'.
我發(fā)現(xiàn)"Woocommerce 中基于用戶角色和付款方式的百分比折扣" 答案非常符合我的需要,但不知道如何修改代碼以滿足我的需要,因為它還包含基于付款方式的條件并僅在結(jié)帳時顯示折扣,但我也需要將其顯示在購物車中.
I found "Percentage discount based on user role and payment method in Woocommerce" answer that is very neer of what I need, but don't know how to modify the code to feet my needs, as it contains also a condition based on payment method and displaying the discount only at checkout, but I need it to display in cart as well.
推薦答案
以下代碼將對公司"用戶角色(在購物車和結(jié)帳時)應(yīng)用 10% 的折扣:
The following code will apply a 10% discount for 'company' user role (on cart and checkout):
// Applying conditionally a discount for a specific user role
add_action( 'woocommerce_cart_calculate_fees', 'discount_based_on_user_role', 20, 1 );
function discount_based_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 = 10;
$discount = $cart->get_subtotal() * $percentage / 100; // Calculation
// Applying discount
$cart->add_fee( sprintf( __("Discount (%s)", "woocommerce"), $percentage . '%'), -$discount, true );
}
代碼位于活動子主題(或活動主題)的 functions.php
文件中.它應(yīng)該有效.
Code goes on functions.php
file of your active child theme (or active theme). It should works.
這篇關(guān)于為 Woocommerce 中的特定用戶角色應(yīng)用折扣的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!