I have a WordPress site where I have a "Premium" user role. I want all users with this role to get a 10% discount on Wall pictures and free candles. I want the discounted price to be displayed in both the shop page, and cart/checkout.
I am far from an expert in PHP, but here is my attempt.
My code does not seem to work properly. For example, the free products are not added to the cart.
Is there anyone who can help me resolve this?
Thank you so much for your help :)
function apply_discounts_based_on_user_role_and_product_type( $cart ) {
if ( is_user_logged_in() ) {
$user_roles = wp_get_current_user()->roles;
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item['data']->get_name() === 'Wall Picture' ) {
if ( in_array( 'premium', $user_roles ) ) {
$discount = $cart_item['data']->get_price() * 0.1;
$cart->add_fee( 'Premium Discount', -$discount, true );
}
} elseif ( $cart_item['data']->get_name() === 'Candle' ) {
if ( in_array( 'premium', $user_roles ) ) {
$cart->remove_cart_item( $cart_item_key );
}
}
}
}
}
add_action( 'woocommerce_cart_calculate_fees', 'apply_discounts_based_on_user_role_and_product_type' );
function update_product_price_based_on_user_role( $price, $product ) {
if ( is_user_logged_in() ) {
$user_roles = wp_get_current_user()->roles;
if ( $product->get_name() === 'Wall Picture' ) {
if ( in_array( 'premium', $user_roles ) ) {
$discounted_price = $product->get_price() * 0.9;
return wc_price( $discounted_price );
}
} elseif ( $product->get_name() === 'Candle' ) {
if ( in_array( 'premium', $user_roles ) ) {
return __('Free', 'text-domain');
}
}
}
return $price;
}
add_filter( 'woocommerce_get_price_html', 'update_product_price_based_on_user_role', 10, 2 );
Note that all Fees are only displayed in cart and checkout pages, but it's not possible technically to display them in the products (shop, product archives, single products or mini-cart).
So it's better to change the product price in cart (to discount the price) and to display it as discounted everywhere else (shop, single product, cart, mini cart and checkout). For the free product that is auto added, we display "Free" and set the price to zero.
In the first function, you need to define the product to be discounted and the free product by their IDs (but not by their names).
The code:
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.