Home / Admin / Generate a virtual coupon when order is completed.
Duplicate Snippet

Embed Snippet on Your Site

Generate a virtual coupon when order is completed.

This snippet will generate a new virtual coupon for a coupon that you've enabled virtual coupon feature on.

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', 152); // Change the ID with the COUPON ID that have virtual coupon enabled
    $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);
    $virtual_coupon->save();
    }
add_action( 'woocommerce_order_status_completed', 'acfwp_create_virtual_coupon', 20, 2 );

Comments

Add a Comment