Protecting custom template pages on WordPress

Protecting custom template pages on WordPress

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

No Comments