wooccommerce应用优惠券编程错误


woocommerce apply coupon programmatically bug

这是我正在使用的代码:

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;

我遇到的问题是,当我转到结账页面时,优惠券仍然会被应用。它没有应用在购物车上,这是所需的结果,但我不希望在这种情况下应用它。

有什么帮助吗?

根据您的解释,听起来您应该使用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 );
}