Forked from ipokkel/restrict_specific_posts_to_specific_users.php
Created
May 22, 2025 13:34
-
-
Save kimwhite/4269e863de797339811ba5362decccbd 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 | |
/** | |
* 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/ | |
*/ | |
/** | |
* Restrict post access to specific email addresses, user IDs, or roles. | |
*/ | |
function restrict_specific_posts_to_specific_users_or_emails( $hasaccess, $thepost, $theuser, $post_membership_levels ) { | |
/* SETTINGS */ | |
// Set your post/page IDs here | |
$posts_array = array( 40 ); // integers only | |
// Set the user IDs that have exclusive access | |
$allowed_user_ids = array( 275, 13, 274 ); | |
// Set email addresses allowed access | |
$allowed_user_emails = array( | |
'[email protected]', | |
'[email protected]', | |
'[email protected]', | |
); | |
// Set allowed roles | |
$allowed_user_roles = array( 'editor', 'administrator' ); | |
/* END SETTINGS */ | |
$thepost_id = $thepost->ID; | |
// First restrict access to these posts for everyone | |
if ( in_array( $thepost_id, $posts_array ) ) { | |
$hasaccess = false; | |
// Grant access if user ID is allowed | |
if ( in_array( $theuser->ID, $allowed_user_ids ) ) { | |
return true; | |
} | |
// Grant access if email is in allowed list | |
if ( in_array( strtolower( $theuser->user_email ), array_map( 'strtolower', $allowed_user_emails ) ) ) { | |
return true; | |
} | |
// Grant access if role is allowed | |
foreach ( $allowed_user_roles as $role ) { | |
if ( in_array( $role, (array) $theuser->roles ) ) { | |
return true; | |
} | |
} | |
} | |
return $hasaccess; | |
} | |
add_filter( 'pmpro_has_membership_access_filter', 'restrict_specific_posts_to_specific_users_or_emails', 10, 4 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment