Created
November 18, 2015 15:00
-
-
Save chrisvanpatten/e09675d7fda009450f68 to your computer and use it in GitHub Desktop.
Function to check if a WooCommerce order contains a free trial (via the Subscriptions extension)
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 | |
/** | |
* Loop through an order's items and see if there's a free trial set | |
* | |
* @param WC_Order $order | |
* @return bool|WP_Error | |
*/ | |
function custom_order_has_trial( $order ) { | |
if ( ! $order instanceof WC_Order ) | |
return new WP_Error( 'invalid_order', 'This order is invalid.' ); | |
// Grab all items in an order | |
if ( $items = $order->get_items() ) { | |
// Loop through the items | |
foreach( $items as $item_id => $item_values ) { | |
// Verify the product information is everything we expect | |
if ( is_array( $item_values['item_meta'] ) && $product_id = $item_values['item_meta']['_product_id'][0] ) { | |
// Check each product for a trial length | |
if ( class_exists( 'WC_Subscriptions_Product' ) && WC_Subscriptions_Product::get_trial_length( $product_id ) > 0 ) { | |
// Return early if a product has a trial length | |
return true; | |
} | |
} | |
} | |
// Otherwise, we return false | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks very much for this, well written and works as expected!