Skip to content

Instantly share code, notes, and snippets.

@ipokkel
Last active February 24, 2025 10:40
Show Gist options
  • Save ipokkel/6358d2c847fd6612b95b4e33167ea5ab to your computer and use it in GitHub Desktop.
Save ipokkel/6358d2c847fd6612b95b4e33167ea5ab to your computer and use it in GitHub Desktop.
Restrict post access to only certain members that has access to a members only post.
<?php
/**
* Allow post access for specific members (users) only.
*
* 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 allow_post_access_for_specific_users_only( $hasaccess, $post, $user, $levels ) {
$allowed_user_ids = array( 1, 2, 3 ); // set allowed user IDs here
$restricted_post_ids = array( 18, 93, 157, 265 ); // set your post IDs here
// return if no access or no level required.
if ( ! $hasaccess || empty( $levels ) ) {
return $hasaccess;
}
// Only apply restrictions for specific posts
if ( ! in_array( $post->ID, $restricted_post_ids ) ) {
return $hasaccess;
}
// Only apply restrictions for specific users
if ( ! empty( $user->ID ) && ! in_array( $user->ID, $allowed_user_ids ) ) {
return false;
}
return $hasaccess;
}
add_filter( 'pmpro_has_membership_access_filter', 'allow_post_access_for_specific_users_only', 10, 4 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment