Woocommerce applies coupon software bug

This is the code I'm using:

if (!is_admin()):
add_action( 'woocommerce_before_cart', 'apply_matched_coupons' );
//add_action('woocommerce_before_cart_table', 'apply_matched_coupons');
//add_action('woocommerce_before_checkout_form', 'apply_matched_coupons');

function apply_matched_coupons() {
global $woocommerce;
$coupon_code = 'somecodehere';

if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

    if ( $woocommerce->cart->cart_contents_total >= 1 ) {
        $woocommerce->cart->add_discount( $coupon_code );
        wc_print_notices();
    }

}

endif;

The problem I am facing is that when I go to the verification page, the coupon is still applied. It does not apply to the cart, which is the desired result, but I do not want it to be applied at all in this state.

Any help?

+4
source share
1 answer

, , woocommerce_add_to_cart, , . , is_admin(), , ... , .

- :

add_action( 'woocommerce_add_to_cart', 'apply_matched_coupons' );

function apply_matched_coupons() {
    // If the current user is a shop admin
    if ( current_user_can( 'manage_woocommerce' ) ) return;
    // If the user is on the cart or checkout page
    if ( is_cart() || is_checkout() ) return;

    $coupon_code = 'somecodehere';

    if ( WC()->cart->has_discount( $coupon_code ) ) return;

    WC()->cart->add_discount( $coupon_code );
}
+4

Source: https://habr.com/ru/post/1616001/


All Articles