在Woocommerce成功购买后更改优惠券电子邮件限制

时间:2018-02-01 19:38:04

标签: wordpress woocommerce

我希望基本上将优惠券代码限制为首次购买后在Woocommerce中应用优惠券代码的用户。

到目前为止我所拥有的:

    function change_meta_on_purchase( $order_id ) {

    $order = new WC_Order( $order_id );
    if( $order->get_used_coupons() ) {

    update_post_meta( $coupon_id, 'customer_email', $emailrestrict );

        }

}

add_action( 'woocommerce_order_status_processing', 'change_meta_on_purchase' );

我认为我一定是错的" get_used_coupons"但我需要他们曾经受到限制的优惠券。

1 个答案:

答案 0 :(得分:1)

以下是使用Woocommerce版本3+ CRUD setters and getters methods将客户电子邮件设置为订单获得“处理”状态时使用的优​​惠券的电子邮件限制的正确和现代方式:

add_action( 'woocommerce_order_status_processing', 'coupon_email_restriction_on_purchase', 20, 2 );
function coupon_email_restriction_on_purchase( $order_id, $order ) {
    $applied_coupons = $order->get_used_coupons();
    if( count( $applied_coupons ) == 0 )
        return; // Exit if there is no coupons

    // Get the Customer billing email
    $customer_email = $order->get_billing_email();

    foreach( $applied_coupons as $coupon_code ){
        // Get an instance of the WC_Coupon object
        $coupon = new WC_Coupon( $coupon_code );

        // Get email restrictions (even if is an empty array)
        $email_restrictions = $coupon->get_email_restrictions();
        // Add the customer email to the restrictions array
        $email_restrictions[] = $customer_email;
        // set the new array of email restrictions
        $coupon->set_email_restrictions( $email_restrictions );

        // Save the coupon data
        $coupon->save();
    }
}

代码进入活动子主题(或活动主题)的function.php文件。

这应该有效。