Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ipokkel/4eb72310157d458363bab993a2a18981 to your computer and use it in GitHub Desktop.
Save ipokkel/4eb72310157d458363bab993a2a18981 to your computer and use it in GitHub Desktop.
<? php
/**
* Restrict post access to specific user IDs or user Roles.
*
* 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 restrict_specific_posts_to_specific_users( $hasaccess, $thepost, $theuser, $post_membership_levels ) {
/* 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' );
/* END SETTINGS - No further editing required */
// get the post ID
$thepost_id = $thepost->ID;
// Let's start by restricting these posts for everyone
if ( in_array( $thepost_id, $posts_array ) ) {
$hasaccess = false;
}
// Let's check if the user should have access to our custom restricted posts.
if ( in_array( $theuser->ID, $allowed_user_ids ) ) {
return true;
}
// 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) $theuser->roles ) ) {
//Give access if the user has an allowed role
return true;
}
}
return $hasaccess;
}
add_filter( 'pmpro_has_membership_access_filter', 'restrict_specific_posts_to_specific_users', 10, 4 );
@ipokkel
Copy link
Author

ipokkel commented Feb 8, 2022

Users can also be redirected from custom restricted posts using the template_redirect hook.
https://gist.github.com/ipokkel/caa9e743a1e6c1fe711732c5cc077ea9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment