Page visibility private displays 404 error (4 posts)

  1. ajcke
    Posted 2 years ago #

    When a user who is not logged in navigates to a page that is marked private they receive a 404 error page. I'd like the page to display a kind reminder to please login to view this page.

    I tried adding the following to the page loop, but a non logged in user still gets the 404 error page.

    if ($post->post_status == "private" && !is_user_logged_in()) {
        echo "You must be logged in to view this page.";
    } else if( $post->post_status == "private" && is_user_logged_in() ) {
        // Page code goes here
  2. ajcke
    Posted 2 years ago #

    I've tried adding the code above and the code below to the page loop right after <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

    The code below still returns the 404 error. Am I putting the code in the wrong place?

    	$slug = basename($_SERVER['REQUEST_URI']);
    	$query = 'SELECT * FROM wp_posts WHERE post_name = "'.$slug.'" LIMIT 1';
    	$page_query = $wpdb->get_results($query, OBJECT);
    	$private = ( is_object($page_query[0]) && $page_query[0]->post_status == 'private' );
    <?php if ( !$private ) { ?>
    	<h1>Error 404 - Page Not Found</h1>
    	<p>Please use the main navigation or the back button on your browser to find what you're looking for.</p>
    <?php } else { ?>
    	<h1>Authorization required - please log in.</h1>
    	<?php get_template_part('login'); ?>
    <?php } ?>
  3. ajcke
    Posted 2 years ago #

    I also tried adding the code in the second post to my 404.php file. It just displays

    Error 404 - Page Not Found
    Please use the main navigation or the back button on your browser to find what you're looking for.

  4. latro666
    Posted 1 year ago #

    Hi there, Bit of thread necromancy but it should help searchers as i needed to do this and came on this thread.

    I worked out a way of doing this myself after much head scratching, its not very elegant but should do the trick. Its along the same lines as above.

    The 404 template does not provide you with a queried post to work with if the post is private but WordPress still does do all the query string and SQL formulation for you! So you can in effect re-query this and check the post thus:

    $requery = $wpdb->get_results($wp_query->request);
    if(count($requery) == 1 && $requery[0]->post_status == 'private'){
        //we have a single post and it is private
        //data empty or not private just kick out a normal 404
        echo("404 page not found");
    } ?>

    Just plop that in 404.php in your main content div and should work.

    You might wanna apply some args to wp_login_form to redirect to said page after login. http://codex.wordpress.org/Function_Reference/wp_login_form

Topic Closed

This topic has been closed to new replies.

About this Topic