【问题标题】:woocommerce apply coupon programmatically bugwoocommerce 以编程方式应用优惠券错误
【发布时间】:2015-11-16 00:46:29
【问题描述】:

这是我正在使用的代码:

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;

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

有什么帮助吗?

【问题讨论】:

  • 我很困惑你在说什么“条件”。你能用某种用户故事来解释发生的结果和预期的结果吗?即用户访问购物车,发生 X,然后她继续结帐,发生 Y,等等
  • @rnevius 当然,我什至不确定我在做什么工作,因为我认为这是以某种方式缓存的。好的。这是大图:添加到购物车时添加优惠券代码。但是,如果您是购物车或结帐页面上的商店管理员或经理,请不要使用优惠券。一旦我知道它的工作原理,下一个阶段就是随机添加它,如果您不是商店管理员或经理,但我仍在处理它

标签: php wordpress woocommerce


【解决方案1】:

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

【讨论】:

  • 你太棒了。我什至可以从我的角度看出事情在哪里变得过于复杂。现在我需要重构 WC()->cart->add_discount( $coupon_code );随机运行。非常感谢朋友。
猜你喜欢
  • 2013-03-22
  • 2019-04-05
  • 2013-04-04
  • 1970-01-01
  • 2020-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多