Created
June 3, 2025 09:23
-
-
Save dwanjuki/03e0c80fad38a084cdebf37f2c893e2d to your computer and use it in GitHub Desktop.
Show old members their last level and hide other levels from active members on levels page.
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 | |
/** | |
* Show old members their last level and hide other levels from active members on levels page. | |
* | |
* 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_hide_levels_for_active_and_old_members( $levels ) { | |
// Bail if no levels. | |
if ( empty( $levels ) ) { | |
return $levels; | |
} | |
// Bail if the user is not logged in. | |
if ( ! is_user_logged_in() ) { | |
return $levels; | |
} | |
$user_id = get_current_user_id(); | |
// Get user's current levels. | |
$user_levels = pmpro_getMembershipLevelsForUser( $user_id ); | |
// If the user has levels, show these levels only. | |
if ( ! empty( $user_levels ) ) { | |
return $user_levels; | |
} | |
// No active levels, get the user's last level. | |
global $wpdb; | |
$user_last_level_id = $wpdb->get_var( | |
$wpdb->prepare( | |
"SELECT membership_id FROM {$wpdb->pmpro_memberships_users} WHERE user_id = %d ORDER BY id DESC LIMIT 1", | |
$user_id | |
) | |
); | |
// If they had a level in the past, show that level only, else show all levels. | |
if ( ! empty( $user_last_level_id ) ) { | |
$user_last_level_id = intval( $user_last_level_id ); | |
foreach ( $levels as $level_id => $level ) { | |
if ( $user_last_level_id !== $level_id ) { | |
unset( $levels[ $level_id ] ); | |
} | |
} | |
} | |
return $levels; | |
} | |
add_filter( 'pmpro_levels_array', 'my_pmpro_hide_levels_for_active_and_old_members' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment