Didier Didier - 5 months ago 20
PHP Question

Woocommerce change tax rate on coupon use

I'm trying to update my Woocommerce tax rate when a certain coupon is used. For this I'm using this code in my functions.php:

function apply_matched_coupons() {
global $woocommerce;

$coupon_code = '123456';

if ( $woocommerce->cart->has_discount( $coupon_code ) ) {

$tax_class = 'Reduced rate';
}
return $tax_class;
}
add_action( 'woocommerce_product_tax_class','apply_matched_coupons' );


This works perfectly on the frontend, HOWEVER after I put this code in my child theme functions.php I'm getting the following error in the backend when I open the "Products" page in wp-admin:

Fatal error: Call to a member function has_discount() on a non-object in xxxx/xxxx/xxxxx/xxxx/functions.php on line 57


Now I suddenly can't seem to get a list of my products in the backend. The loading of the products is broken after the first product's price.

Any idea how I should modify this code so both the frontend and backend works like it should? I'm a noob at coding so sorry if this is a stupid question!

I searched Google and Stackoverflow and came up with similar code that worked on the frontend but always gave the same error on the backend.

Thanks for the help!

Answer Source

well, first let's tweak your code a bit.

You don't need global $woocommerce; use WC() in place of $woocommerce. And let's add !is_admin() on your if. So it should just work on the frontend.

function apply_matched_coupons() {

    $coupon_code = '123456'; 

    if ( !is_admin() && WC()->cart->has_discount( $coupon_code ) ) {
        $tax_class = 'Reduced rate';
    }
    return $tax_class;
}
add_action( 'woocommerce_product_tax_class','apply_matched_coupons' );