Password Protect Custom Page

I try to password protect my custom page such that before any content is shown the user must enter a password. More specific, in my code below, anything inside the content-div-container should be password protected:

<?php
/*
Template Name: custom_page
*/
?>

<?php get_header(); ?>
<div id="content">

  <div id="main">


<ul class="post">
        <li><b>LATEST POSTS</li>
 <?php
    $args = array('category' => 5, 'post_type' =>  'post');
    $postslist = get_posts( $args );    
    foreach ($postslist as $post) :  setup_postdata($post); 
    ?> 
    <li id="post-<?php the_ID(); ?>">
      <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> 
    <?php the_excerpt(); ?>
    </li>
    <?php endforeach; ?>

</ul> 

</div><!-- end content -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>

I tried to use the approach explained here

Read More

Password protecting a page

but cannot make it work, since I do not know how to wrap my php code into the suggested solution.

Related posts

Leave a Reply

2 comments

  1. When you select password protected option in page back-end, It by-default works for content only. i.e. the_content()

    But if you want to password protect whole page or have a custom template, you need to have the following structure.

    <?php
    global $post;
    get_header();
    
    if ( ! post_password_required( $post ) ) {
          // Your custom code should here
    }else{
        // we will show password form here
        echo get_the_password_form();
    }
    
    ?>
    

    Try using this structure