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 in your WordPress site for logged in users only.
<?php
/**
* Restrict specific posts in your WordPress site for logged in 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 my_restricted_posts_require_user_login() {
global $current_user;
// Allow logged in users.
if ( is_user_logged_in() ) {
return;
}
// Restrict non-users from accessing posts with these IDs:
$restricted_posts = array( 1, 2, 3 );
if ( is_single( $restricted_posts ) ) {
wp_redirect( home_url( 'wp-login.php?redirect_to=' . urlencode( $_SERVER['REQUEST_URI'] ) ) );
} else {
return;
}
}
add_action( 'template_redirect', 'my_restricted_posts_require_user_login' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment