John Davidson

php - Fire function on order creation to remove coupons from parent subscription

0 comments
Message:


I have the following function, I want it fire every time an order for a subscription is created.


I then want it to remove the store credit coupons from the parent subscription (as renewal orders will contain the coupon).


I'm getting the error:



"PHP message: PHP Fatal error: Uncaught Error: Call to undefined method WC_Order_Item_Coupon::get_discount_type()".



Where am I going wrong?


Is it passing in the parent subscription item in the right way?


   function remove_store_credit($subscription) {

$coupons = $subscription->get_items( 'coupon' );
foreach ( $coupons as $coupon ) {
if($coupon->get_discount_type() == "smart_coupon"){
$subscription->remove_coupon( $coupon->get_code() );
}
}

}
add_action('woocommerce_subscription_payment_complete','remove_store_credit',10,1);


My Answer:
It seems like you are trying to remove store credit coupons from the parent subscription when a new order is created for a subscription. To achieve this, you can use the `woocommerce_order_status_completed` hook to trigger your function when an order is completed.

Here is an example code snippet that you can use to achieve this:

php
add_action('woocommerce_order_status_completed', 'remove_store_credit_coupons', 10, 1);

function remove_store_credit_coupons($order_id) {
$order = wc_get_order($order_id);

// Check if the order is for a subscription
if (wcs_order_contains_subscription($order)) {
$subscriptions = wcs_get_subscriptions_for_order($order, array('order_type' => 'parent'));

foreach ($subscriptions as $subscription) {
// Remove store credit coupons from the parent subscription
$coupons = $subscription->get_coupons();

foreach ($coupons as $coupon) {
if ($coupon->is_type('store_credit')) {
$subscription->remove_coupon($coupon->get_code());
}
}
}
}
}


You can add this code to your theme's `functions.php` file or a custom plugin. This code will trigger the `remove_store_credit_coupons` function every time an order is completed. It will then check if the order contains a subscription and remove any store credit coupons from the parent subscription.

Make sure to test this code on a staging site before implementing it on a live site to ensure it works as expected.

Rate this post

3 of 5 based on 5444 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us