I want to generate woocommerce coupon code dynamically.
My requirements is that after complete the order automatically generate one coupon code in admin side woocommerce coupon code list for particular product.
So any one know my above requirement solutions then please help me.
Thanks,
Ketan.
You can used woocommerce_order_status_completed
action hook for order complete. and create post with post type shop_coupon
for coupan using wp_insert_post
. check below code
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 );
Write a function which will fire when an order has been completed or placed using the woocommerce_order_status_completed
or woocommerce_order_status_processing
hook. Inside the function, use wp_insert_post
to create a post of type shop_coupon. Using wp_insert_post, you can specify the title of the coupon, amount etc.