Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davidmutero/c81a68da87a41486eacf237564145857 to your computer and use it in GitHub Desktop.
Save davidmutero/c81a68da87a41486eacf237564145857 to your computer and use it in GitHub Desktop.
PMPro template_redirect redirection based on discount code OR membership level
<?php
/**
* This recipe will redirect users after checkout based on a Discount Code OR their Membership Level.
*
* It hooks into the `template_redirect` action and is useful when the default `pmpro_confirmation_url` filter
* does not work reliably, such as with off-site gateways like Stripe Checkout.
*
* 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_pmpro_redirect_after_checkout() {
if ( ! is_admin() && is_page( pmpro_getOption( 'confirmation_page_id' ) ) && is_user_logged_in() ) {
$user_id = get_current_user_id();
// Get the user's current level.
$membership_level = pmpro_getMembershipLevelForUser( $user_id );
// Get discount code used (most recent).
global $wpdb;
$discount_code = $wpdb->get_var(
$wpdb->prepare(
"SELECT d.code
FROM {$wpdb->prefix}pmpro_discount_codes_uses u
LEFT JOIN {$wpdb->prefix}pmpro_discount_codes d ON u.code_id = d.id
WHERE u.user_id = %d
ORDER BY u.id DESC
LIMIT 1",
$user_id
)
);
// Coupon-based redirect (priority).
if ( $discount_code === 'SC916E8F9CC' ) {
wp_redirect( 'https://example.com/page_1' );
exit;
} elseif ( $discount_code === 'X84HJ8F9CC' ) {
wp_redirect( 'https://example.com/page_2' );
exit;
}
// Membership-level-based redirect.
if ( pmpro_hasMembershipLevel( 2, $user_id ) ) {
wp_redirect( 'https://example.com/level2' );
exit;
} elseif ( pmpro_hasMembershipLevel( 3, $user_id ) ) {
wp_redirect( 'https://example.com/level3' );
exit;
}
}
}
add_action( 'template_redirect', 'my_pmpro_redirect_after_checkout' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment