Skip to content

Instantly share code, notes, and snippets.

@chrisvanpatten
Created November 18, 2015 15:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrisvanpatten/e09675d7fda009450f68 to your computer and use it in GitHub Desktop.
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)
<?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;
}
}
@JonathanPort
Copy link

Thanks very much for this, well written and works as expected!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment