Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jamestrevorlees/c0a0477f1e0acaec1a76b4d74a39dcfd to your computer and use it in GitHub Desktop.
Save jamestrevorlees/c0a0477f1e0acaec1a76b4d74a39dcfd 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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment