Reputation: 4068
This is the code I am 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 issue I am having is that when I go to the checkout page that the coupon still gets applied. It's not applied on the cart which is the desired result but I don't want it applied at all in this condition.
Any help?
Upvotes: 4
Views: 3405
Reputation: 27092
Based on your explanation, it sounds like you should be using the woocommerce_add_to_cart
hook, which is run when a product is successfully added to the cart. I also don't think you should be using is_admin()
, since that just checks if you're on an admin page...not if the current user is an admin.
I would do something like the following:
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 );
}
Upvotes: 5