Skip to content

Instantly share code, notes, and snippets.

@daltonrooney
Last active August 29, 2015 14:07
Show Gist options
  • Save daltonrooney/f69ddd4a673eacf93392 to your computer and use it in GitHub Desktop.
Save daltonrooney/f69ddd4a673eacf93392 to your computer and use it in GitHub Desktop.
Add a downloadable product to a user's account when a WooCommerce Subscription is created
Let's say you run a WooCommerce subscription website, and you'd like to automatically add
a downloadable product to a subscriber's account when they activate their subscription.
Here's one way to do it:
// Free downloadable product with a new subscription
add_action('activated_subscription', 'djr_subscription_activated');
function djr_subscription_activated( $userID ) {
//Change your product ID below
djr_create_order( $userID, 19700 );
}
function djr_create_order( $userID, $productID ) {
$user = get_userdata( $userID );
$args = array(
'customer_id' => $userID,
'customer_note' => 'Free item added via subscription'
);
$create_order = wc_create_order($args);
$pf = new WC_Product_Factory();
$product = $pf->get_product($productID);
$create_order->add_product($product);
if( $product->is_downloadable() ) {
$download_files = $product->get_files();
foreach ( $download_files as $download_id => $file ) {
wc_downloadable_file_permission( $download_id, $product->id, $create_order );
}
}
$create_order->update_status('completed');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment