在WooCommerce网站上,我出售一张礼券,客户可以在那里输入他想要赠送自己的金额,我希望在订单支付后,WooCommerce促销代码会与相应的金额一起创建.
这是我想出来的代码,但似乎根本不起作用.
add_action('woocommerce_order_status_completed', 'custom_promo_code_creation', 10, 1);
function custom_promo_code_creation($order_id) {
$order = wc_get_order($order_id);
$specific_product_id = 2081;
$specific_product_price = 0;
foreach ($order->get_items() as $item_id => $item) {
$product_id = $item->get_product_id();
if ($product_id === $specific_product_id) {
$specific_product_price = $item->get_total();
break;
}
}
if ($specific_product_price > 0) {
$coupon_code = generate_unique_voucher_code();
$expiration_date = strtotime('+3 months'); // Set the expiration to 3 months from now
$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);
if ($new_coupon_id) {
update_post_meta($new_coupon_id, 'discount_type', 'fixed_cart');
update_post_meta($new_coupon_id, 'coupon_amount', $specific_product_price);
update_post_meta($new_coupon_id, 'individual_use', 'yes');
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', $expiration_date);
}
}
}
订单正在正常进行,但没有创建优惠券