0
votes

I am using a function to apply a custom price to products within a certain category based on user role. Here is a shortened example:

function return_custom_discounted_price($price, $product) {

$current_user = wp_get_current_user();
$newPrice = $price;
$prodID = $product->get_id();

     if( in_array('example_customer', $current_user->roles) && !is_admin()){

            if(has_term( 'example-category', 'product_cat', $prodID )){
                $newPrice = $price * .9;
            }

     }
     return $newPrice;
}
add_filter('woocommerce_product_get_price', 'return_custom_discounted_price', 10, 2);

However, if a product in this category is added from a grouped product, the discount is applied twice in the cart. For example if the product was $100, the cart applies:

(100 * .9) * .9 = 81 

when it should just be

100 * .9 = 90

Which is strange because the code works fine if you add the same product by itself and NOT from the grouped product.

I am also using the Product Addons WooCommerce extension on these grouped products. I use jQuery to show/hide child products of the grouped product base off of their add-on selection. The add-on is not applying any cost change.

Why is this happening in the cart?

1
I have tested your code and I don't have this problem… So there is something else that is making the hook run twice.LoicTheAztec
@LoicTheAztec Ok thanks, good to know. I'm looking into the Product Add-ons part. It seems that only items with a product add-on are giving the issue.Seb G
So you can't use that with the items using Product Add-ons, as this plugin is calling the hook… may be try to increase hook priority from 10 to 999…LoicTheAztec
@LoicTheAztec Ah, makes sense. I tried, unfortunately it did not resolve the issue. I'm going to have to find some way around this. Thanks!Seb G

1 Answers

0
votes

With some help from the comments, the issue was found to be the Product Add-on extension calling the hook again in the cart. To fix this, all I had to do was replace the price being changed with the original product price. This way, even if called multiple times, the result will be the same. Below is the working example.

function return_custom_discounted_price($price, $product) {

$current_user = wp_get_current_user();
$newPrice = $price;
$prodID = $product->get_id();
$originalPrice = $product->get_regular_price();

     if( in_array('example_customer', $current_user->roles) && !is_admin()){

            if(has_term( 'example-category', 'product_cat', $prodID )){
                $newPrice = $originalPrice * .9;
            }

     }
     return $newPrice;
}
add_filter('woocommerce_product_get_price', 'return_custom_discounted_price', 999, 2);