Members-Only Subsites
Makes the subsites you list visible only to logged-in members of that site; everyone else is sent to the login page and non-members see a friendly notice.
Opens WPIDE on
Code
if ( ! is_multisite() ) {
return;
}
$wpide_private_sites = array(); // Blog IDs that only members can view, e.g. array( 3, 7 ).
if ( ! in_array( get_current_blog_id(), $wpide_private_sites, true ) ) {
return;
}
add_action( 'template_redirect', function () {
if ( is_user_logged_in() && ( is_user_member_of_blog() || is_super_admin() ) ) {
return;
}
if ( ! is_user_logged_in() ) {
auth_redirect();
}
wp_die( esc_html__( 'This site is only open to its members.' ), esc_html__( 'Members only' ), array( 'response' => 403 ) );
}, 1 );
add_filter( 'rest_authentication_errors', function ( $result ) {
if ( ! empty( $result ) || ( is_user_logged_in() && ( is_user_member_of_blog() || is_super_admin() ) ) ) {
return $result;
}
return new WP_Error( 'wpide_members_only', __( 'This site is only open to its members.' ), array( 'status' => 401 ) );
} );
Notes
List blog IDs in $wpide_private_sites. Feeds and the REST API are covered too; super admins always have access.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.