redirect private child site (on a multisite) to login page if not logged in

Home » Snippets » redirect private child site (on a multisite) to login page if not logged in
0

Created with:

Visibility: 

public

Creator: Jérémy

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php
function wpturbo_redirect_private_site() {
 
    if ( is_user_logged_in() ) {
        return;
    }
 
    global $wpdb;
    $current_blog_id = get_current_blog_id();
    $blog_details = get_blog_details($current_blog_id);
 
    if ( $blog_details->public != '0' || $blog_details->archived == '1' || $blog_details->spam == '1' || $blog_details->deleted == '1' ) {
        return;
    }
 
    wp_redirect( wp_login_url() );
    exit;
}
add_action( 'template_redirect', 'wpturbo_redirect_private_site' );
				

This code uses the template_redirect action to check whether the user is logged into the private child site. If not, they are redirected to the login page using the wp_redirect() function.

First, we check if the user is already logged in. If so, the function returns without taking any further action.

Next, we get the current site ID with the get_current_blog_id() function, and then retrieve the site details using the get_blog_details() function. We check whether the site is private ($blog_details->public != '0'), archived ($blog_details->archived == '1'), spam ($blog_details->spam == '1'), or deleted ($blog_details->deleted == '1'). If any of these conditions are true, we return without redirecting.

Finally, if the site is private and the user is not logged in, we redirect them to the login page using the wp_redirect() function, passing wp_login_url() as the URL to redirect to. This function returns the login URL for the current site. We then exit the function using exit.

Hope this helps!

Register an account to save your snippets or go Pro to get more features.