如何使用编程代码动态生成woocommerce优惠券代码
问题描述:
我想动态生成woocommerce优惠券代码。如何使用编程代码动态生成woocommerce优惠券代码
我的要求是,完成订单后,在管理端自动生成一个优惠券代码woocommerce优惠券代码列表中的特定产品。
所以任何人都知道我的上述要求的解决方案,然后请帮助我。
谢谢, Ketan。
答
您可以使用woocommerce_order_status_completed
操作挂钩完成订单。并使用wp_insert_post
为coupan创建帖子类型为shop_coupon
。检查下面的代码
function action_woocommerce_order_status_completed($order_id) {
$order = wc_get_order($order_id);
$order_items = $order->get_items();
// Iterating through each item in the order
$item_quantity=0;
foreach ($order_items as $item_id => $item_data) {
$item_quantity=$order->get_item_meta($item_id, '_qty', true);
if($item_quantity>1){
$product_ids[]=$item_data['product_id'];
$coupon_code = 'UNIQUECODE'.$order_id.$item_id; // Code
$amount = '10'; // Amount
$discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product
$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);
// Add meta
update_post_meta($new_coupon_id, 'discount_type', $discount_type);
update_post_meta($new_coupon_id, 'coupon_amount', $amount);
update_post_meta($new_coupon_id, 'individual_use', 'no');
update_post_meta($new_coupon_id, 'product_ids',$product_ids);
update_post_meta($new_coupon_id, 'exclude_product_ids', '');
update_post_meta($new_coupon_id, 'usage_limit', '');
update_post_meta($new_coupon_id, 'expiry_date', '');
update_post_meta($new_coupon_id, 'apply_before_tax', 'yes');
update_post_meta($new_coupon_id, 'free_shipping', 'no');
unset($product_ids);
}
}
};
// add the action
add_action('woocommerce_order_status_completed', 'action_woocommerce_order_status_completed', 10, 1);
答
编写一个函数,当订单已完成或使用woocommerce_order_status_completed
或woocommerce_order_status_processing
挂钩进行放置时将触发该功能。在函数内部,使用wp_insert_post
创建shop_coupon类型的帖子。使用wp_insert_post,您可以指定优惠券的名称,金额等。
+0
谢谢尼尔k,为您的重播。 我会尝试你的解决方案并更新你。 谢谢。 – Ketan
感谢Ankur,为您的重播。 我会尝试你的解决方案并更新你。 谢谢。 – Ketan
嗨Ankur, 在我的functions.php文件中添加上面的代码后,网站无法正常工作在前端和后端显示空白白屏。 所以,你可以请检阅你的上述代码,并在这里更新我。 谢谢。 – Ketan
$ coupon_code ='UNIQUECODE'$ order_id;这一行错误。请在UNIQUECODE和$ order_id之间加上'.'。请检查已编辑的答案 –