Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create WooCommerce coupons programmatically - a proof of concept - Experiment creating virtual coupons for WooCommerce. This is a proof of concept that will be developed to verify a coupon code with an external source. https://www.damiencarbery.com/2018/10/create-woocommerce-coupons-programmatically-a-proof-of-concept/
<?php
/*
Plugin Name: Virtual Coupons for WooCommerce
Plugin URI: https://www.damiencarbery.com/2018/10/create-woocommerce-coupons-programmatically-a-proof-of-concept/
Description: Experiment with a virtual coupon, based on a conversation with Mark Davenport.
Author: Damien Carbery
Author URI: https://www.damiencarbery.com
Version: 0.2
*/
function dcwd_is_coupon_code_valid( $coupon_code ) {
if ( 0 === strpos( $coupon_code, 'gr-' ) ) { // Coupon codes are lowercased.
// TODO: Also check that the coupon is available for use and not already used.
return true;
}
return false;
}
// Inspired by https://www.mootpoint.org/blog/create-woocommerce-coupon-programmatically/
add_filter ( 'woocommerce_get_shop_coupon_data', 'dcwd_create_virtual_coupon', 10, 2 );
function dcwd_create_virtual_coupon( $false, $data ) {
// Do not interfere with coupon creation and editing.
if ( is_admin() ) {
return $false;
}
$coupon_code_valid = false;
$coupon_settings = null;
if ( dcwd_is_coupon_code_valid( $data ) ) {
$coupon_code_valid = true;
}
if ( $coupon_code_valid ) {
// Create a coupon with the properties you need
$coupon_settings = array(
'discount_type' => 'percent', // 'fixed_cart', 'percent' or 'fixed_product'
'amount' => 50, // value or percentage.
'expiry_date' => '2019-09-01', // YYYY-MM-DD
'individual_use' => false,
'product_ids' => array(),
'exclude_product_ids' => array(),
'usage_limit' => '',
'usage_limit_per_user' => '1',
'limit_usage_to_x_items' => '',
'usage_count' => '',
'free_shipping' => false,
'product_categories' => array(),
'exclude_product_categories' => array(),
'exclude_sale_items' => false,
'minimum_amount' => '',
'maximum_amount' => '',
'customer_email' => array(),
);
return $coupon_settings;
}
return $false;
}
// From: https://stackoverflow.com/questions/49675017/woocommerce-get-shop-coupon-data-being-called-3-times
add_action('woocommerce_applied_coupon', 'action_applied_coupon' );
function action_applied_coupon( $coupon_code ) {
if ( dcwd_is_coupon_code_valid( $coupon_code ) ) {
error_log( "Coupon '$coupon_code' has been applied. Mark as used." );
}
}
add_action('woocommerce_removed_coupon', 'action_removed_coupon' );
function action_removed_coupon( $coupon_code ) {
if ( dcwd_is_coupon_code_valid( $coupon_code ) ) {
error_log( "Coupon '$coupon_code' has been removed. Mark as UNused." );
}
}
@joglomedia
Copy link

using this approach, is the virtual coupon not stored to the WooCommerce coupon?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment