Home / Admin / Auto Generate Virtual Coupon After a Customer Completed an Order
Duplicate Snippet

Embed Snippet on Your Site

Auto Generate Virtual Coupon After a Customer Completed an Order

Code Preview
php
<?php
/**
 * Generate a virtual coupon when order is completed.
 * 
 * @param int $order_id Order ID. 
 */
function acfwp_create_virtual_coupon( $order_id ) {
    $order = wc_get_order( $order_id );
    $customer_id = $order->get_customer_id();
	$create_date = date( 'Y-m-d H:i:s', current_time('timestamp'));
    $expire_date = date( 'Y-m-d H:i:s', current_time('timestamp') + (5 * DAY_IN_SECONDS) );
	
    /**
    * Generate a single virtual coupon for a coupon.
    * NOTE: the coupon needs to enable virtual coupon first.
    */
    $virtual_coupon = new ACFWP\Models\Objects\Virtual_Coupon();
    $virtual_coupon->set_prop('coupon_id', 1033); // Update the Coupon ID with your Virtual Coupon enabled Coupon
    $virtual_coupon->set_prop('status', 'pending');
    $virtual_coupon->set_prop( 'user_id', $customer_id); // optional
	$virtual_coupon->set_datetime_prop('date_created', $create_date); 
    $virtual_coupon->set_datetime_prop('date_expire', $expire_date); // optional, set when the coupon will expire
    $virtual_coupon->save();
	$order->update_meta_data('virtual_coupons', $virtual_coupon->get_coupon_code());
	$order->save_meta_data();
    }
add_action( 'woocommerce_order_status_processing', 'acfwp_create_virtual_coupon', 20, 2 );
//You can use another action hook for other order status for example:  'woocommerce_order_status_on-hold'
add_filter('woocommerce_thankyou_order_received_text', 'woo_change_order_received_text', 10, 2 );
function woo_change_order_received_text( $str, $order ) {
    $new_str = $str . 'Here a coupon code for your next order: ' . $order->get_meta('virtual_coupons');
    return $new_str;
}

Comments

Add a Comment