Skip to content

Instantly share code, notes, and snippets.

@thomasgriffin
Last active January 1, 2016 13:49
Show Gist options
  • Save thomasgriffin/8153754 to your computer and use it in GitHub Desktop.
Save thomasgriffin/8153754 to your computer and use it in GitHub Desktop.
Force the use of only one license per user in EDD. This prevents the need to manage multiple licenses if you are selling products in tiers (such as upgrading licenses). This will create a license if none exist, and if one exists, it will simply upgrade that license each time a new purchase is made and reference the most recent purchase for downl…
<?php
// Force licenses to be created manually so that only one license is ever assigned to a user at a given time.
remove_action( 'edd_complete_download_purchase', array( edd_software_licensing(), 'generate_license' ), 0, 3 );
add_action( 'edd_complete_purchase', 'tgm_possibly_generate_license', 11 );
function tgm_possibly_generate_license( $payment_id ) {
// Check to see if the current user has already purchased a license. If not, generate the license as normal.
$payment_data = edd_get_payment_meta( $payment_id );
$user_info = maybe_unserialize( $payment_data['user_info'] );
$download = current( maybe_unserialize( $payment_data['downloads'] ) );
$edd_sl = edd_software_licensing();
// Get all user purchases. If we have purchases, simply modify the license and update it accordingly.
$purchases = edd_get_users_purchases( $user_info['id'] );
if ( $purchases && ! empty( $purchases ) ) {
$first_purchase = end( $purchases );
$license = $edd_sl->get_licenses_of_purchase( $first_purchase->ID );
// If no license exists yet for the purchase, create it now, otherwise update it.
if ( ! $license ) {
$edd_sl->generate_license( $download['id'], $payment_id );
} else {
// Update license properties to reflect the latest update/purchase.
$license_update = array();
$license_update['ID'] = $license[0]->ID;
$license_update['post_title'] = get_the_title( $download['id'] ) . '-' . $user_info['email'];
wp_update_post( $license_update );
// Update amount of time until license expires.
$edd_sl->set_license_expiration( $license[0]->ID, strtotime( '+1 year' ) );
// Update other important meta for handling licenses.
update_post_meta( $license[0]->ID, '_edd_sl_download_id', $download['id'] );
update_post_meta( $license[0]->ID, '_edd_sl_payment_id', $payment_id );
}
} else {
$edd_sl->generate_license( $download['id'], $payment_id );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment