Last active
February 8, 2022 13:26
-
-
Save ipokkel/caa9e743a1e6c1fe711732c5cc077ea9 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* Only allow specific users or user roles to view a set of specific posts | |
* and redirect users that doesn't meet the set criteria away from the post. | |
* | |
* 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 redirect_from_post_restricted_to_specific_user_id_or_role() { | |
/* SETTINGS */ | |
// Set your post/page id's here | |
$posts_array = array( 2, 35, 156 ); // array elements must be integers and not strings | |
// Set the user ID's that has exclusive access to these posts here | |
$allowed_user_ids = array( 29, 121, 134 ); | |
// Set roles here that will receive access to all member content. | |
$allowed_user_roles = array( 'editor', 'administrator' ); | |
// Set URL to which not allowed users should be redirected to. | |
$redirect_to_url = home_url(); | |
/* END SETTINGS - No further editing required */ | |
// Let's get the user | |
global $current_user; | |
// get the post ID | |
$post_id = get_the_id(); | |
// Let's check if this if we need to manage this post | |
if ( ! in_array( $post_id, $posts_array ) ) { | |
return; | |
} | |
// Let's check if the user should have access to our custom restricted posts. | |
if ( in_array( $current_user->ID, $allowed_user_ids ) ) { | |
return; | |
} | |
// This user's ID wasn't included in the allowed users array, let's check if they belong to an allowed role. | |
foreach ( $allowed_user_roles as $key => $role ) { | |
if ( in_array( $role, (array) $current_user->roles ) ) { | |
//Give access if the user has an allowed role | |
return; | |
} | |
} | |
// This user didn't meet the restriction criteria, let's redirect them | |
wp_redirect( $redirect_to_url ); | |
exit; | |
} | |
add_action( 'template_redirect', 'redirect_from_post_restricted_to_specific_user_id_or_role' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Post content can also be restricted using the
pmpro_has_membership_access_filter
hook.https://gist.github.com/ipokkel/4eb72310157d458363bab993a2a18981