Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kimwhite/4269e863de797339811ba5362decccbd to your computer and use it in GitHub Desktop.
Save kimwhite/4269e863de797339811ba5362decccbd 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/
*/
/**
* 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