如何以编程方式自动在Woocommerce中应用优惠券?

时间:2013-04-12 10:20:02

标签: php wordpress woocommerce

您好我希望在购物车总额为25欧元或以上时自动将20%的优惠券折扣应用于购物车 - 我查看了之前用户的代码并尝试修改并将其放入功能中.php,但它对我不起作用 - 对于我做错了什么的任何帮助/?这是我放入functions.php;

的代码
/* Mod: 20% Discount for orders over €25 
Works with code added to child theme: woocommerce/cart/cart.php lines 13 - 14: which gets $subtotal of cart:
        global $subtotal;
        $subtotal= $woocommerce->cart->subtotal;
*/
add_action('woocommerce_before_cart_table', 'discount_when_order_greater_25');
function discount_when_order_greater_25( ) {
    global $woocommerce;
    global $subtotal;
    if( $subtotal >= 25 ) {
        $coupon_code = '20';
        if (!$woocommerce->cart->add_discount( sanitize_text_field( $coupon_code ))) {
            $woocommerce->show_messages();
        }
        echo '<div class="woocommerce_message"><strong>Your order is over €25 so a 20% Discount has been Applied!</strong> Your total order weight is <strong>' . $total_weight . '</strong> lbs.</div>';
    }
}

/* Mod: 20% Discount for orders under €25  */
add_action('woocommerce_before_cart_table', 'remove_discount_when_order_less_25');
function remove_discount_when_order_less_25( ) {
    global $woocommerce;
    global $subtotal;
    if( $subtotal < 25 ) {
        $coupon_code = '20';
        $woocommerce->cart->get_applied_coupons();
        if (!$woocommerce->cart->remove_coupons( sanitize_text_field( $coupon_code ))) {
            $woocommerce->show_messages();
        }
        $woocommerce->cart->calculate_totals();
    }
}

1 个答案:

答案 0 :(得分:0)

我一直在使用旨在实现此目的的免费WooCommerce插件(在woo Commerce购物车中自动应用优惠券代码)遇到麻烦。 其次,我在Google上容易找到的论坛帖子不完整,并引发了未处理的异常。

因此,这是截至2020-11-03的工作代码示例。您可以将其放在Wordpress子主题的文件夹functions.php文件中:

add_action('woocommerce_before_cart', 'auto_apply_discount_coupon');
function auto_apply_discount_coupon() {
    $wc_coupon = new WC_Coupon('DEMO-90JOURS'); // get intance of wc_coupon which code is "DEMO-90JOURS"
    if (!$wc_coupon || !$wc_coupon->is_valid()) {
        return;
    }

    $coupon_code = $wc_coupon->get_code();
    if (!$coupon_code) {
        return;
    }

    global $woocommerce;
    if (!$woocommerce->cart->has_discount($coupon_code)) {
        // You can call apply_coupon() without checking if the coupon already has been applied,
        // because the function apply_coupon() will itself make sure to not re-add it if it was applied before.
        // However this if-check prevents the customer getting a error message saying
        // “The coupon has already been applied” every time the cart is updated.
        if (!$woocommerce->cart->apply_coupon($coupon_code)) {
            $woocommerce->wc_print_notices();
            return;
        }

        wc_print_notice('<div class="woocommerce_message"><strong>Le coupon ' . $coupon_code . ' a été appliqué avec succès!</strong></div>', 'notice');
    }
}