Woocommerce首单免运费

tencent promotion
原创作者: Fengjiajun

Woocommerce首单免运费

function firstTimeShopper() {
    global $woocommerce;
    $coupon_code = 'XXXXXXXXX'; //这里是免运费的优惠券代码
    if (is_user_logged_in()) {
        $current_user = wp_get_current_user();
        if (!$current_user)
            return;
        $hasOrderedBefore = get_user_meta($current_user->ID, 'paying_customer', true);
        if (!$hasOrderedBefore) {
            if ($woocommerce->cart->has_discount(sanitize_text_field($coupon_code)))// If coupon has been already been added remove it.
                if (!$woocommerce->cart->remove_coupons(sanitize_text_field($coupon_code)))
                    $woocommerce->show_messages();
            if (!$woocommerce->cart->add_discount(sanitize_text_field($coupon_code))) {
                $woocommerce->show_messages();
            } else {
                $woocommerce->clear_messages();
                $woocommerce->add_message("Hi there! <b>Because this is your first order we've applied a free shipping discount.</b> No hidden catches, we just want to say thanks!");
                $woocommerce->show_messages();
            }
            $woocommerce->cart->calculate_totals();// Recalculate totals.
        } else {
            if ($woocommerce->cart->has_discount(sanitize_text_field($coupon_code))) {// Is not user's first time shopping
                if ($woocommerce->cart->remove_coupons(sanitize_text_field($coupon_code)))
                    $woocommerce->show_messages();
                $woocommerce->cart->calculate_totals();//Recalculate totals.
            }
        }
    }
}
add_action('woocommerce_before_cart', 'firstTimeShopper');
add_action('woocommerce_before_checkout_form', 'firstTimeShopper');