在Woocommerce编程方式将优惠券(Apply a coupon programmatical

2019-08-18 15:26发布

在Woocommerce我试图找到一种方法,10%的折扣适用于整个客户的订单,如果在车的重量超过100磅。 我一部分的方式来实现这一目标。 对于下一步,我正在寻找一种方式,通过的functions.php以编程方式申请通过动作/挂机优惠券代码。

看来,我可以使用函数woocommerce_ajax_apply_coupon做到这一点( http://docs.woothemes.com/wc-apidocs/function-woocommerce_ajax_apply_coupon.html ),但我不确定如何使用它。

到目前为止,我已经修改cart.php得到的所有产品的总重量的车,我已经创建了一个应用折扣(如果手动输入)的优惠券,我已经添加了一些代码添加到functions.php检查的重量并显示一条消息给用户。

编辑:偏码除去,包括在下面的解决方案完成的代码。


感谢您的指导Freney。 下面是它成功地适用于当条件满足的优惠券,并删除它时,它不再满足工作的最终结果:

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

/* Mod: Remove 10% Discount for weight less than or equal to 100 lbs */
add_action('woocommerce_before_cart_table', 'remove_coupon_if_weight_100_or_less');
function remove_coupon_if_weight_100_or_less( ) {
    global $woocommerce;
    global $total_weight;
    if( $total_weight <= 100 ) {
        $coupon_code = '999';
        $woocommerce->cart->get_applied_coupons();
        if (!$woocommerce->cart->remove_coupons( sanitize_text_field( $coupon_code ))) {
            $woocommerce->show_messages();
        }
        $woocommerce->cart->calculate_totals();
    }
}

Answer 1:

首先,创建一个折扣券(通过http://docs.woothemes.com/document/create-a-coupon-programatically/ ):

$coupon_code = 'UNIQUECODE'; // Code - perhaps generate this from the user ID + the order ID
$amount = '10'; // Amount
$discount_type = 'percent'; // Type: fixed_cart, percent, fixed_product, percent_product

$coupon = array(
    'post_title' => $coupon_code,
    'post_content' => '',
    'post_status' => 'publish',
    'post_author' => 1,
    'post_type'     => 'shop_coupon'
);    

$new_coupon_id = wp_insert_post( $coupon );

// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'no' );
update_post_meta( $new_coupon_id, 'product_ids', '' );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '1' );
update_post_meta( $new_coupon_id, 'expiry_date', '' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );

那么优惠券适用于您的订单:

if (!$woocommerce->cart->add_discount( sanitize_text_field( $coupon_code )))
    $woocommerce->show_messages();

如果失败的各种原因之一TRUE如果折扣成功,FALSE:那最后一个函数返回一个BOOL值。



Answer 2:

我用这个解决方案,但它包含了一个错误的OP写的。 如果用户跳过预览车,径直到结账的形式,它并不适用优惠券。 这里是我的解决方案。

// Independence day 2013 coupon auto add
// Add coupon when user views cart before checkout (shipping calculation page).
add_action('woocommerce_before_cart_table', 'add_independence_day_2013_coupon_automatically');

// Add coupon when user views checkout page (would not be added otherwise, unless user views cart first).
add_action('woocommerce_before_checkout_form', 'add_independence_day_2013_coupon_automatically');

// Check if php function exists.  If it doesn't, create it.
if (!function_exists('add_independence_day_2013_coupon_automatically')) {

    function add_independence_day_2013_coupon_automatically() {

        global $woocommerce;
        $coupon_code = 'independencedaysale';
        $bc_coupon_start_date = '2013-06-30 17:00:00';
        $bc_coupon_end_date = '2013-07-08 06:59:59';

        // Only apply coupon between 12:00am on 7/1/2013 and 11:59pm on 7/7/2013 PST.
        if ((time() >= strtotime($bc_coupon_start_date)) &&
            (time() <= strtotime($bc_coupon_end_date))) {

            // If coupon has been already been added remove it.
            if ($woocommerce->cart->has_discount(sanitize_text_field($coupon_code))) {

                if (!$woocommerce->cart->remove_coupons(sanitize_text_field($coupon_code))) {

                    $woocommerce->show_messages();

                }

            }

            // Add coupon
            if (!$woocommerce->cart->add_discount(sanitize_text_field($coupon_code))) {

                $woocommerce->show_messages();

            } else {

                $woocommerce->clear_messages();
                $woocommerce->add_message('Independence day sale coupon (10%) automatically applied');
                $woocommerce->show_messages();

            }

            // Manually recalculate totals.  If you do not do this, a refresh is required before user will see updated totals when discount is removed.
            $woocommerce->cart->calculate_totals();

        } else {

            // Coupon is no longer valid, based on date.  Remove it.
            if ($woocommerce->cart->has_discount(sanitize_text_field($coupon_code))) {

                if ($woocommerce->cart->remove_coupons(sanitize_text_field($coupon_code))) {

                    $woocommerce->show_messages();

                }

                // Manually recalculate totals.  If you do not do this, a refresh is required before user will see updated totals when discount is removed.
                $woocommerce->cart->calculate_totals();

            }

        }

    }

}


Answer 3:

二千零十九分之二千零十七因为Woocommerce 3

在一个钩函数以下压缩代码将添加基于购物车显示的自定义消息总重量的折扣(优惠券)。 如果客户改变购物车的物品代码将检查车中的物品取出优惠(优惠券),如果车的重量是定义的权重下。

代码:

add_action('woocommerce_before_calculate_totals', 'discount_based_on_weight_threshold');
function discount_based_on_weight_threshold( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Your settings
    $coupon_code      = 'onweight10'; // Coupon code
    $weight_threshold = 100; // Total weight threshold

    // Initializing variables
    $total_weight     = $cart->get_cart_contents_weight();
    $applied_coupons  = $cart->get_applied_coupons();
    $coupon_code      = sanitize_text_field( $coupon_code );

    // Applying coupon
    if( ! in_array($coupon_code, $applied_coupons) && $total_weight >= $weight_threshold ){
        $cart->add_discount( $coupon_code );
        wc_clear_notices();
        wc_add_notice( sprintf(
            __("Your order is over %s so a %s Discount has been Applied! Your total order weight is %s.", "woocommerce"),
            wc_format_weight( $weight_threshold ), '10%', '<strong>' . wc_format_weight( $total_weight ) . '</strong>'
        ), "notice");
    }
    // Removing coupon
    elseif( in_array($coupon_code, $applied_coupons) && $total_weight < $weight_threshold ){
        $cart->remove_coupon( $coupon_code );
    }
}

代码放在您的活动子主题的function.php文件(或活动主题)。 测试和工程。



文章来源: Apply a coupon programmatically in Woocommerce