Snippets: Restrict WordPress Content To Logged In Users Only

// Example 1: Restrict access to whole site and redirect to the wordpress login page
add_action( 'template_redirect', function() {

	// Front end only and allow access to ajax functions
	if ( is_admin() || wp_doing_ajax() ) {
		return;
	}

	// Redirect all pages to the login page if user isn't logged in
	if ( ! is_user_logged_in() ) {
		wp_redirect( esc_url( wp_login_url() ), 307 );
	}

} );

// Example 2: Restrict access to specific pages
add_action( 'template_redirect', function() {

	// Get global post
	global $post;

	// Prevent access to page with ID of 2 and all children of this page
	$page_id = 170;
	if ( is_page() && ( $post->post_parent == $page_id || is_page( $page_id ) ) ) {

		// Set redirect to true by default
		$redirect = true;

		// If logged in do not redirect
		// You can/should place additional checks here based on user roles or user meta
		if ( is_user_logged_in() ) {
			$redirect = false;
		}

		// Redirect people without access to login page
		if ( $redirect ) {
			wp_redirect( esc_url( wp_login_url() ), 307 );
		}


	}

} );

Snippet Type: PHP

Posted Under: Other

All PHP snippets should be added via a child theme's functions.php file.