Show A Page Only To Logged-In Users – WordPress

Below is a simple WordPress code that will show a page only to logged-in users.

Add this code to your child theme’s functions.php file or via a plugin that allows custom functions to be added, such as the Dessky Snippets plugin. Please don’t add custom code directly to your parent theme’s functions.php file as this will be overwritten completely when you update the theme.

function redirect_if_not_logged_in() {
	/*
	* Returns true when the Pages displayed is either post ID 52,
	* or post_name "about-me", or post_title "Contact".
	*/
	$protected_page = is_page( array( 52, 'about-me', 'Contact' ) );

	if ( $protected_page && ! is_user_logged_in() ) {
		/**
		 * If you want to redirect to a specific page, use this:
		 * wp_safe_redirect( get_permalink( get_page_by_path( 'login' ) ) );
		 */
		wp_safe_redirect( home_url() );
		exit();
	}
}
add_action( 'template_redirect', 'redirect_if_not_logged_in' );
womble.ed womble_leilani@mailxu.com gilchrestcoralee@mailxu.com