Created
July 1, 2023 19:02
-
-
Save webfixlab/a1983dcfe1e64837d859d423b2a2724d to your computer and use it in GitHub Desktop.
Creating Dynamic Order Status Changes in WooCommerce
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 | |
/** | |
* Change order status to Extras Only if all ordered items from Extras category | |
* Change order status to Proc/ Gift Box if product addon gif box selected YES | |
* Change order status to Intl Order if order is not from US/Canada | |
*/ | |
function change_status_giftbox_and_extrasonly( $order_id ) { | |
if ( ! $order_id ) return; | |
// Get order object | |
$order = wc_get_order( $order_id ); | |
// Ensure the order is 'processing' | |
if ($order->get_status() !== 'processing') return; | |
// Specific categories: the term name/term_id/slug. Several could be added, separated by a comma | |
$categories = array( 'extras' ); | |
// Flag | |
$found = true; | |
$gift_found = false; | |
$country = ""; | |
// grab country name | |
if ($order->get_shipping_country() == "US" OR $order->get_shipping_country() == "Canada" OR $order->get_shipping_country() == "CA" OR $order->get_billing_country() == "US" OR $order->get_billing_country() == "Canada" OR $order->get_billing_country() == "CA") { | |
// printf( esc_html__( 'Non-international Order.', 'woocommerce' ) ); | |
$country = "domestic"; | |
}else { | |
$country = "international"; | |
} | |
// Loop through order items | |
foreach ( $order->get_items() as $item ) { | |
// PROC/GIFT BOX STATUS | |
// Here, we can get the value by a specific metakey | |
if ( $item->get_meta( "_Gift Ready Milk Collection Kit" ) ) { | |
// Test if string contains the word | |
if(strpos($item->get_meta( "_Gift Ready Milk Collection Kit" ), "No") === false){ | |
$found = false; | |
$gift_found = true; | |
break; | |
} | |
} | |
// EXTRAS ONLY STATUS | |
// Product ID | |
$product_id = $item->get_variation_id() > 0 ? $item->get_variation_id() : $item->get_product_id(); | |
// Has term (product category) | |
if ( !has_term( $categories, 'product_cat', $product_id ) ) { | |
$found = false; | |
} | |
} | |
// without wc- prefix, change order status | |
if ( $found ) { | |
$order->update_status( 'extras' ); | |
}elseif ( $gift_found ) { | |
$order->update_status( 'process-gift-box' ); | |
}elseif ( !$found && !$gift_found && $country == "international" ) { | |
$order->update_status( 'intl-order' ); | |
} | |
} | |
add_action( 'woocommerce_thankyou', 'change_status_giftbox_and_extrasonly', 10, 1 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can find the code explanation on this article Creating Dynamic Order Status Changes in WooCommerce: An In-Depth Guide