Created
May 26, 2022 13:21
-
-
Save dparker1005/b0e56d48f3e241220302d37949218e5e to your computer and use it in GitHub Desktop.
Keeps Stripe subscription attached to membership level after purchasing an Addon Package.
This file contains hidden or 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 | |
/** | |
* Keeps Stripe subscription attached to membership level after purchasing an Addon Package. | |
* | |
* You can add this recipe to your site by creating a custom plugin | |
* or using the Code Snippets plugin available for free in the WordPress repository. | |
* Read this companion article for step-by-step directions on either method. | |
* https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/ | |
*/ | |
function my_pmproap_keep_membership_subscription_linked( $user_id, $morder ) { | |
if ( empty( $_REQUEST['ap'] ) ) { | |
// User isn't purchasing an addon package, so we don't need to keep a subscription linked. | |
return; | |
} | |
// Get all previous memberships for the user, including inactive. | |
$prev_levels = pmpro_getMembershipLevelsForUser( $user_id, true ); // True to also get inactive levels. | |
if ( count( $prev_levels ) === 1 ) { | |
// This is the user's first purchase. We don't need to keep a subscription linked. | |
return; | |
} | |
$new_level = end( $prev_levels ); | |
$prev_level = prev( $prev_levels ); | |
// Check if the user purchased the same level that they previously had. | |
if ( $new_level->id !== $prev_level->id ) { | |
// They purchased a different level, so we don't need to keep a subscription linked. | |
return; | |
} | |
// Check if the new level that they purchased is already recurring. | |
if ( pmpro_isLevelRecurring( $new_level ) ) { | |
// The new level is already recurring, so we don't need to keep a subscription linked. | |
return; | |
} | |
// Make sure that the old level that they purchased was recurring. | |
if ( ! pmpro_isLevelRecurring( $prev_level ) ) { | |
// The old level isn't recurring, so we don't need to keep a subscription linked. | |
return; | |
} | |
// Move subscription data from the old level to the new level. | |
global $wpdb; | |
$wpdb->get_results( $wpdb->prepare( "UPDATE $wpdb->pmpro_memberships_users SET billing_amount = %d, cycle_number = %d, cycle_period = %s WHERE user_id = %d AND status = 'active'", $prev_level->billing_amount, $prev_level->cycle_number, $prev_level->cycle_period, $user_id ) ); | |
} | |
add_action( 'pmpro_after_checkout', 'my_pmproap_keep_membership_subscription_linked', 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment