You can use PHP code like this in your child themes functions file or custom functionality/code snippets plugin.
No need for plugins or coupon codes, this code applies the discount based on the user I.D.
add_action('woocommerce_cart_calculate_fees', 'apply_discount_for_specific_user'); function apply_discount_for_specific_user() { // Get the current user $user = wp_get_current_user(); // Replace with the specific user ID you want to target $specific_user_id = 5; // Change 5 to the ID of the user // Check if the current user's ID matches the specific user ID if ($user->ID == $specific_user_id) { // Define the discount amount $discount = 10; // 10 units of currency, e.g., $10 // Add the discount to the cart WC()->cart->add_fee(__('Special Discount', 'your-text-domain'), -$discount); } }
Usage – Settings
Swap out the value for the $specific_user_id
from 5 and the value for $discount
variable from 10.
And here’s the result for user with the id of 5 who gets a $10 discount on the cart page and at checkout.
About The Code
The code uses the woocommerce_cart_calculate_fees action hook which is located inside the class-wc-cart.php file in WooCommerce. Its wrapped in the calculate_fees()
function which is used in the class-wc-cart-totals.php file to get fee objects from the cart.
You can use this hook to add fee’s and apply discounts conditionally in WooCommerce.
Here’s more code which uses the woocommerce_cart_calculate_fees hook.
Was This Tutorial Helpful?