0
votes

I added new custom post type 'giftcard' and extended WooCommerce simple product by adding checkbox 'Gift Card'

Whenever order status changed to 'processing' and it contains product type giftcard, it creates new giftcard post by following code

function status_order_processing( $order_id ) {
   $order = wc_get_order( $order_id );
   $items = $order->get_items();

   foreach ( $items as $item ) {
    $is_gift_card = get_post_meta( $item['product_id'], '_woo_giftcard', true );

    if($is_gift_card == 'yes'){
$token = base64_encode(openssl_random_pseudo_bytes(32));
            $token = bin2hex($token);
            $hyphen = chr(45);
    $uuid =  substr($token, 0, 8).$hyphen
            .substr($token, 8, 4).$hyphen
            .substr($token,12, 4).$hyphen
            .substr($token,16, 4).$hyphen
            .substr($token,20,12);

   $gift_card = array(
    'post_title'    => $uuid,
    'post_status'   => 'publish',
    'post_type'     => 'giftcard',
);
   $gift_card_id = wp_insert_post( $gift_card, $wp_error );
   update_post_meta( $gift_card_id, 'woo_gift_card_amount', (int)$item['total'] );

}
}
add_action( 'woocommerce_order_status_processing', 'status_order_processing' );

New post name is a token generated in above code and save item total in meta field 'woo_gift_card_amount'.

Is there any way if I enter giftcard post type token in coupon field and it subtracts amount from Order amount according to meta field 'woo_gift_card_amount' of that post.

Any help would be appreciated.

1

1 Answers

1
votes

Coupons are also a custom post. To use your gift card token/uuid as woocommerce coupon, you will need to insert it as a new post in shop_coupon post type.

A quick example (this should go inside your status_order_processing function, or you can use separate function - whichever way suits you):

$coupon_code = $uuid;
$amount = (int)$item['total'];
$discount_type = 'fixed_cart'; //available types: 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 );

if ( $new_coupon_id ) {
    //add coupon/post 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, 'expiry_date', $expiry_date);
    //update_post_meta($new_coupon_id, 'usage_limit', '1');
    //update_post_meta($new_coupon_id, 'individual_use', 'no');
    //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', '' );
    //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' );
}