Override core woocommerce class

I have to override following WooCommerce core class methods:

  • WC_Cart()->get_discounted_price()
  • WC_Coupon()->validate_cart_excluded_sale_items()

What I’m trying to do is WooCommerce does not allow to have a non-sale product and a sale product in the cart and then apply the coupon code.
When the following option is checked on coupon Usage restriction tab

Check this box if the coupon should not apply to items on sale. Per-item coupons will only work if the item is not on sale. Per-cart coupons will only work if there are no sale items in the cart.

I have to make coupon applied to only non-sale products even if any sale products in the cart. The coupon will only affect non-sale products amount and simply ignore sale products amount.

Now I got workaround with this thing and I have to override with my own custom implementation with above methods. And as you see there are no hooks to work with either.

I also tried this solution without any luck

  • Override woocomerce files from includes

1 Answer
1

1) There is a hook for the first one:

You can use the apply_filters

Their code:

apply_filters( 'woocommerce_get_discounted_price', $price, $values, $this );

Your code:

add_filter( 'woocommerce_get_discounted_price', function($price, $values, $this)
{
     //return whatever you want
},10,3
);
//*PHP 5.3 and up

you can pass whatever function you want into the second parameter of the add_filter function. Check out the Codex for details.

https://codex.wordpress.org/Function_Reference/add_filter

2) The second one will be very hacky and probably not recommended:

Though there are no hooks on the validate_cart_excluded_sale_items() function, the outcome is dependent up a transient value that you can override (if you are careful to put it back when you are done.

You can adjust the outcome of this functon: wc_get_product_ids_on_sale()

their code:

// Load from cache
    $product_ids_on_sale = get_transient( 'wc_products_onsale' );
...
set_transient( 'wc_products_onsale', $product_ids_on_sale, DAY_IN_SECONDS * 30 );

what you could do:

store the current $product_ids_on_sale from the get_transient function

then set it to an empty array

set_transient( 'wc_products_onsale', [], DAY_IN_SECONDS * 30 );

then set it back when the validation has passed

set_transient( 'wc_products_onsale', $your_stored_product_ids_on_sale, DAY_IN_SECONDS * 30 );

AGAIN, I DO NOT RECOMMEND THIS, BUT I WANTED TO SHOW THAT IT IS POSSIBLE

It sounds like you should just get a better promotion for the sale

Leave a Comment