Last active
April 16, 2021 19:03
-
-
Save kimcoleman/97208fb28128b6594b0c8862a286c254 to your computer and use it in GitHub Desktop.
Redirect member away from the Member Profile page if they do not have access to view this member's profile.
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 | |
/* | |
* Redirect member away from the Member Profile page if they do not have access to view this member's profile. | |
* | |
*/ | |
function my_template_redirect_member_profile_permissions() { | |
global $pmpro_pages; | |
if ( empty( $pmpro_pages ) || empty( $pmpro_pages['profile'] ) || ! is_page( $pmpro_pages['profile'] ) ){ | |
return; | |
} | |
if ( ! function_exists( 'pmpro_hasMembershipLevel' ) ) { | |
return; | |
} | |
$pu = sanitize_text_field( $_REQUEST[ 'pu' ] ); | |
if ( is_user_logged_in() ) { | |
// Get the current user's ID. | |
$user_id = get_current_user_id(); | |
// Get the profile user. | |
$profile_user = get_user_by( 'slug', $_REQUEST['pu'] ); | |
// Build a comma-separated list of the profile user's levels. | |
$profile_user_level = pmpro_getMembershipLevelForUser( $profile_user->ID ); | |
// Build the logic of whether to redirect away. | |
$redirect_away = false; | |
if ( pmpro_hasMembershipLevel( 1, $user_id ) && $profile_user_level->ID != 1 ) { | |
// Can only see other Level 1 users; | |
$redirect_away = true; | |
} | |
if ( pmpro_hasMembershipLevel( 2, $user_id ) && ! in_array( $profile_user_level->ID, array( 1, 2 ) ) ) { | |
// Can only see Level 1 or 2 users; | |
$redirect_away = true; | |
} | |
if ( pmpro_hasMembershipLevel( 3, $user_id ) && ! in_array( $profile_user_level->ID, array( 1, 2, 3 ) ) ) { | |
// Can only see Level 1 or 2 users; | |
$redirect_away = true; | |
} | |
} | |
if ( ! empty( $redirect_away ) ) { | |
// Redirect back to the directory page if available. Otherwise, redirect to home. | |
if ( ! empty( $pmpro_pages['directory'] ) ) { | |
wp_redirect( get_permalink( $pmpro_pages['directory'] ) ); | |
} else { | |
wp_redirect( home_url() ); | |
} | |
exit; | |
} | |
return; | |
} | |
add_action( 'template_redirect', 'my_template_redirect_member_profile_permissions' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment