Using WordPress ‘post_password_required()’ PHP function

The post_password_required() WordPress PHP function determines whether a post requires a password and if the correct password has been provided.

Usage

To use the post_password_required() function, provide a post ID or a WP_Post object. If not provided, the global $post is used by default.

post_password_required( $post );

Parameters

  • $post (int|WP_Post|null) (Optional) – An optional post. The global $post is used if not provided. Default is null.

More information

See WordPress Developer Resources: post_password_required

Examples

Basic usage of post_password_required()

This example checks if the current post requires a password and displays a message if it does.

if ( post_password_required() ) {
echo 'This post is password protected!';
}

Displaying a custom password form

This example displays a custom password form if the post is password protected.

if ( post_password_required() ) {
echo get_the_password_form();
echo '<p>Please enter the password to view this post.</p>';
}

Displaying content if the password is provided

This example shows the post content only if the correct password has been provided.

if ( !post_password_required() ) {
the_content();
} else {
echo 'This post is password protected!';
}

Checking password requirement for a specific post

This example checks if a specific post with the ID $post_id requires a password.

if ( post_password_required( $post_id ) ) {
echo 'This post is password protected!';
}

Using post_password_required() in a loop

This example checks for password protection within a loop and displays the content accordingly.

if ( have_posts() ) {
while ( have_posts() ) {
the_post();

if ( post_password_required() ) {
echo 'This post is password protected!';
} else {
the_content();
}
}
}