php - How do I programmatically apply a coupon in Woocommerce for first order made by a customer? -
in woocommerce i'm trying find way apply 20% discount first order made new customer. appears can use functions woocommerce_after_checkout_validation
, check_new_customer_coupon
doesn't work.
function.php:
add_action('woocommerce_after_checkout_validation','check_new_customer_coupon', 0); function check_new_customer_coupon(){ global $woocommerce; // might change name of coupon $new_cust_coupon_code = 'test'; $has_apply_coupon = false; foreach ( wc()->cart->get_coupons() $code => $coupon ) { if($code == $new_cust_coupon_code) { $has_apply_coupon = true; } } if($has_apply_coupon) { if(is_user_logged_in()) { $user_id = get_current_user_id(); // retrieve orders $customer_orders = get_posts( array( 'meta_key' => '_customer_user', 'meta_value' => $user_id, 'post_type' => 'shop_order', 'numberposts'=> -1 ) ); if(count($customer_orders) > 0) { $has_ordered = false; $statuses = array('wc-failed', 'wc-cancelled', 'wc-refunded'); // loop thru orders, if order not falled failed, cancelled or refund consider valid foreach($customer_orders $tmp_order) { $order = wc_get_order($tmp_order->id); if(!in_array($order->get_status(), $statuses)) { $has_ordered = true; } } // if customer ordered, remove coupon if($has_ordered == true) { wc()->cart->remove_coupon( $new_cust_coupon_code ); wc_add_notice( sprintf( "coupon code: %s applicable new customer." , $new_cust_coupon_code), 'error' ); return false; } } else { // customer has no order, valid use coupon return true; } } else { // new user valid return true; } } }
maybe can workaround putting on site :
with coupon xxxxxx 20 % off first commande
https://docs.woothemes.com/document/coupon-management/
and in coupon management put limitation 1 per user ?
Comments
Post a Comment