将优惠券添加到现有的WooCommerce订阅

时间:2020-05-15 12:47:07

标签: php wordpress woocommerce hook-woocommerce woocommerce-subscriptions

我已经启动了一个推荐计划,该计划为用户提供25英镑的折扣优惠券代码,该代码非常有用,但不适用于既有的订户,我该如何进行续订并应用自动优惠券,以便订阅也可以从折扣中受益。 / p>

我可以用woocommerce_new_order实现吗?

编辑:

最后更新以帮助他人使用我的代码,以利用下面的优惠券使用现有的订户:

// discount subscription renewals

function discount_subscription_renewals($billing_email){

    $query_args = array(
    'posts_per_page' => -1,
    'post_type'      => 'shop_coupon',
    'post_status'    => 'publish',
    'orderby'        => array( 'title' => 'ASC' ),
    'meta_query'     => array(
                        array(
                            'key'     => 'discount_type',
                            'value'   => 'fixed_cart',
                        ),
                    ),
    );

    $coupons = get_posts( $query_args );
    $coupon_code = false;
    $discount   = 0;
    foreach ( $coupons as $coupon ) {

        $customer_email = array($coupon->customer_email[0]);

        $amount       =  $coupon->coupon_amount;
        $usage_count  =  $coupon->usage_count;
        $usage_limit   =  $coupon->usage_limit;



        if (in_array($billing_email,$customer_email) && ($usage_count < $usage_limit)){

          $coupon_code = $coupon->post_title;
          break;
          //$discount   += $amount;
        }  

    }   
    return $coupon_code;
}


function apply_discount_on_renewal_order_created( $renewal_order, $subscription ) {

    $order           = new WC_Order($renewal_order->get_id() );
    $billing_email   = $order->get_billing_email();
    $coupon_code   = discount_subscription_renewals($billing_email);
    if ($coupon_code){
        $order->apply_coupon($coupon_code);
        //$order->set_total( $order->get_total() - $coupon_amount );
    }    
    return $order;
}

add_filter( 'wcs_renewal_order_created', 'apply_discount_on_renewal_order_created', 10, 2 );

1 个答案:

答案 0 :(得分:1)

function apply_discount_on_renewal_order_created( $renewal_order, $subscription ) {

    $order           = new WC_Order( $renewal_order->get_id() );
    $coupon_amount   = 25;
    $order->set_total( $order->get_total() - $coupon_amount );
    return $order;
}

add_filter( 'wcs_renewal_order_created', 'apply_discount_on_renewal_order_created', 10, 2 );