Require Users To Login Before Viewing Post



Some of websites require login before viewing some pages to hide some important data from anonymous users. So if you also want to require users to login before viewing post in WordPress, here is the solution. Just copy the following code in functions.php file of your theme.

function locked_posts() {

	global $post;
	if (!is_single())
		return;

	$ids = array(213, 215); // array of post ID
	if (in_array((int)$post->ID, $ids) && !is_user_logged_in()) {
		auth_redirect();
	}
}

Now open your theme’s single.php file and copy following code before get_header(); line like:

    locked_posts();
    get_header();

Currently we have just two post ids to require login, you can add more post ID’s in $ids array. When any user try to open or view these post he will be redirected to login page and after login redirect to post detail page.

I hope this will help you.