Snippets: Restrict WordPress Content To Logged In Users Only

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 nor redirect
		// You can/should place additional checks here based on user roles or user meta
		if ( is_user_logged_in() ) {
			$redirect = false;
		}

		
		// Redirect people witout access to homepage
		if ( $redirect ) {
			wp_redirect( esc_url( home_url( '/' ) ), 307 );
		}


	}

} );

Snippet Type: PHP

Posted Under: Other

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