1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
<?php
namespace SIW\WooCommerce\Admin;
use SIW\Properties;
class Coupon {
const DISCOUNT_TYPE = 'percent';
public static function init() {
$self = new self();
add_filter( 'woocommerce_order_actions', [ $self, 'add_order_action'] );
add_action( 'woocommerce_order_action_siw_create_coupon', [ $self, 'create_coupon'] );
add_action( 'woocommerce_order_status_completed', [ $self, 'create_coupon'] );
}
public function add_order_action( array $actions ) {
global $theorder;
if ( $theorder->is_paid() && empty( wc_get_coupon_id_by_code( $theorder->get_order_number() ) ) ) {
$actions['siw_create_coupon'] = __( 'Creëer kortingscode', 'siw' );
}
return $actions;
}
function create_coupon( $order ) {
if ( is_int( $order ) ) {
$order = new \WC_Order( $order );
}
if ( ! is_a( $order, '\WC_Order' ) ) {
return;
}
$application_number = $order->get_order_number();
if ( 0 !== wc_get_coupon_id_by_code( $application_number ) ) {
return;
}
$coupon = new \WC_Coupon();
$coupon->set_props( [
'code' => $application_number,
'discount_type' => self::DISCOUNT_TYPE,
'email_restrictions' => $order->get_billing_email(),
'amount' => empty( $order->get_coupon_codes() ) ? Properties::DISCOUNT_SECOND_PROJECT : Properties::DISCOUNT_THIRD_PROJECT,
'description' => $order->get_formatted_billing_full_name(),
'date_expires' => '',
'usage_limit' => 1,
]);
$coupon->save();
$order->add_order_note( 'Kortingscode aangemaakt' );
}
}