Screen Shot 2013-04-22 at 12.16.15

Protecting a page in WordPress is as easy as it can get. There is this option on the editing panel (top right) where one can check “protected” and decide on a password. WordPress will them automagically substitute the_content() and the_excerpt() with the password form and prepend “Protected” to the title.

But how do you protect a page with a custom template?

Custom templates are a way of creating your own layout an assigning them to wordpress pages. Setting the page to protected does not ensure that your custom code will be protected, only if using the_content() within your personal loop. Therefore you should keep the code you’d like to protected inside an if sentence using the wordpress function post_password_required(). The codex says this function returns FALSE when there is no need for password or the password has already been entered correctly (cookies!), and TRUE to prompt for the password.

The following code was the solution to my problem today:

global $post;
if ( !post_password_required( $post ) ) {
    // All cotent I would like to protect
} else {
    echo get_the_password_form(); // to show the password form

Author: Bea Cabrera

Freelance Filmmaker with a passion for big cities, snowboard, cinema and a weakness for the smell of freshly ground coffee. Engineer & Graphic Designer in a previous life, loving and living both: art and technology.  

Leave a Reply

Your email address will not be published.

You may use these <abbr title="HyperText Markup Language">html</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


This site uses Akismet to reduce spam. Learn how your comment data is processed.