How to create a coupon from canceled booking in WooCommerce Bookings?
-
Hi
I have a client that wants to automatically issue a coupon or store credits when a booking is canceled. I have looked at the ‘woocommerce_booking_cancelled’ action, but I’m not sure how to connect that to the function for making the coupon. Any ideas?With this code, I have been able to echo the right info to the screen when I cancel a booking. Now I just have to find out how to create a coupon in the right customer account.
Any thoughts?This is the code I have put in functions.php file in the child theme:
add_action(‘woocommerce_booking_cancelled’, ‘cancelled_info’, 10, 2);
function cancelled_info($booking_id, $booking)
{
// Create random coupon code
$characters = “ABCDEFGHJKMNPQRSTUVWXYZ23456789”;
$char_length = “8”;
$random_cupon_code = substr(str_shuffle($characters), 0, $char_length);
// Get the user ID from the Booking ID
$user_id = get_post_field(‘post_author’, $booking_id);
$coupon_code = $random_cupon_code;
$download_credits = get_post_meta($booking_id, ‘_booking_cost’, true);
/**
* Create a coupon programatically
*/
$amount = $download_credits; // 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’, ”);
update_post_meta($new_coupon_id, ‘exclude_product_ids’, ”);
update_post_meta($new_coupon_id, ‘usage_limit’, ‘1’);
update_post_meta($new_coupon_id, ‘usage_limit_per_user’, ‘1’);
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’);
echo “Verdi: ” . $download_credits . “coupon id: ” . $new_coupon_id . “coupon code: ” . $coupon_code;
}
- The topic ‘How to create a coupon from canceled booking in WooCommerce Bookings?’ is closed to new replies.