Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dwanjuki/ddf6216c4fd755db4e042214be5021e1 to your computer and use it in GitHub Desktop.
Save dwanjuki/ddf6216c4fd755db4e042214be5021e1 to your computer and use it in GitHub Desktop.
Restrict specific posts/pages in your WordPress site for members of a level, redirect other visitors away
<?php // copy from below
/**
* Restrict specific posts/pages in your WordPress site for members of a level
*
* 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 my_restricted_posts_require_membership_level() {
global $post;
// bail if PMPro isn't active
if ( ! function_exists( 'pmpro_hasMembershipLevel' ) ) {
return;
}
// Allow members of specified level ID(s)
if ( pmpro_hasMembershipLevel( 1 ) ) {
return;
}
// The level specified above is required to access these posts
$restricted_posts = array( 651, 652, 769 ); // post ids here
if ( in_array( $post->ID, $restricted_posts ) ) {
wp_redirect( home_url() ); // redirect to home
exit;
}
}
add_action( 'template_redirect', 'my_restricted_posts_require_membership_level' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment