Last active
December 24, 2018 09:48
-
-
Save goranefbl/b7f22a9ef79eff5a2f0cc48b5640f221 to your computer and use it in GitHub Desktop.
Refer a friend by WPGens - Woocommerce Subscription discount
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter('wcs_new_order_created','gens_renewal_order_created', 10, 2 ); | |
function gens_renewal_order_created($order, $subscription){ | |
$_user_id = $order->get_user_id(); | |
$user_info = get_userdata($_user_id); | |
$user_email = $user_info->user_email; | |
$args = array( | |
'posts_per_page' => -1, | |
'post_type' => 'shop_coupon', | |
'post_status' => 'publish', | |
'meta_query' => array( | |
'relation' => 'AND', | |
array( | |
'key' => 'customer_email', | |
'value' => $user_email, | |
'compare' => 'LIKE' | |
), | |
array( | |
'relation' => 'OR', | |
array( | |
'key' => 'usage_count', | |
'value' => '0', | |
'compare' => 'LIKE' | |
), | |
array( | |
'key' => 'usage_count', | |
'compare' => 'NOT EXISTS' | |
) | |
) | |
), | |
); | |
$coupons = get_posts( $args ); | |
if(empty($coupons)) { | |
return $order; | |
} | |
$coupons_obj = new WC_Coupon($coupons[0]->ID); | |
$amount = $coupons_obj->get_amount(); | |
$type = $coupons_obj->get_discount_type(); // fixed_cart or percent | |
$coupons_amount = $coupons_obj->set_usage_count(1); | |
$coupons_obj->save(); | |
if( $type == "percent") { | |
$discount = $order->get_total() * ( $amount / 100); | |
} else { | |
$discount = $amount; | |
} | |
$item = new WC_Order_Item_Fee(); | |
$item->set_props( array( | |
'name' => "Referral applied", | |
'tax_class' => NULL, | |
'total' => -$discount, | |
'total_tax' => 0, | |
'order_id' => $order->get_id(), | |
) ); | |
$item->save(); | |
$order->add_item( $item ); | |
$order->update_taxes(); | |
$order->calculate_totals( true ); | |
return $order; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From class-wc-order-item-fee.php
I checked and for now the total may be negative as used here. But we do not know if this will be accepted in the future.
So right now I am using a
$newOrder->set_total( $newOrder->get_total() - $discountAmount );
followed by
$newOrder->add_order_note( __( 'Coupon applied', 'textdomain' ) );