问题描述
在Woocommerce中,我试图找到一种对新客户的第一笔订单应用20%折扣的方法.看来我可以使用函数woocommerce_after_checkout_validation
和check_new_customer_coupon
来执行此操作,但是它不起作用.
In Woocommerce I'm trying to find a way to apply a 20% discount to the first order made by a new customer. It appears that I can use the functions woocommerce_after_checkout_validation
and check_new_customer_coupon
to do this but it doesn't work.
function.php:
add_action('woocommerce_after_checkout_validation','check_new_customer_coupon', 0);
function check_new_customer_coupon(){
global $woocommerce;
// you might change the name of your coupon
$new_cust_coupon_code = 'test';
$has_apply_coupon = false;
foreach ( WC()->cart->get_coupons() as $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 all 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 the order is not falled into failed, cancelled or refund then it consider valid
foreach($customer_orders as $tmp_order) {
$order = wc_get_order($tmp_order->ID);
if(!in_array($order->get_status(), $statuses)) {
$has_ordered = true;
}
}
// if this customer already ordered, we remove the coupon
if($has_ordered == true) {
WC()->cart->remove_coupon( $new_cust_coupon_code );
wc_add_notice( sprintf( "Coupon code: %s is only applicable for new customer." , $new_cust_coupon_code), 'error' );
return false;
}
} else {
// customer has no order, so valid to use this coupon
return true;
}
} else {
// new user is valid
return true;
}
}
}
推荐答案
也许您可以通过在网站上放置类似内容来解决此问题:
Maybe you can do a workaround by putting something like this on the site :
使用优惠券XXXXXX,您的第一个命令获得20%的折扣
With the coupon XXXXXX get 20 % off for your first commande
https://docs.woothemes.com/document/coupon-management/
在优惠券管理中,每个用户限制为1个?
and in coupon management you put a limitation to 1 per user ?
这篇关于我如何在Woocommerce中以编程方式将优惠券用于客户的第一笔订单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!