post_password_required()
Checks if the post is password protected or not. Also checks the correctness of the password if a password is set for the post.
Hooks from the function
Returns
true|false. Boolean: true if a password is required to view the post or false if the post is not password protected.
Usage
if( post_password_required( $post ) ){ ... }
- $post(integer/object) (required)
- ID of the post or an object with post data.
Default: global variable $post
Examples
#1 Show posts only if user has post password
$master_post = get_post();
if ( post_password_required( $master_post->ID ) ) {
echo '<p>THIS POST IS PASSWORD PROTECTED: PLEASE ENTER IT!</p>';
echo get_the_password_form();
}
else {
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
the_content();
echo '<hr>';
}
}
else {
echo '<p>Nothing Found!</p>';
}
}
Note: Something else you have to watch is cookies being set once the password has been used once, makes debugging a nightmare, (tip), use an Incognito Window when testing out your code.
See: get_the_password_form().
#2 Only valid for password-protected posts
Let's assume that post 443 is password protected, then:
if( post_password_required( 443 ) ){
echo "This post is password protected!";
}
Changelog
| Since 2.7.0 | Introduced. |