post_password_required()WP 2.7.0

Whether post requires password and correct password has been provided.

Hooks from the function

Return

true|false. false if a password is not required or the correct password cookie is present, true otherwise.

Usage

post_password_required( $post );
$post(int|WP_Post|null)
An optional post. Global $post used if not provided.
Default: null

Examples

0

#1 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!";
}
0

#2 Show posts only if user has post password

I looked long and hard in trying to find a working example of his function, (couldn’t!)

$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(),

Changelog

Since 2.7.0 Introduced.

post_password_required() code WP 6.4.3

function post_password_required( $post = null ) {
	$post = get_post( $post );

	if ( empty( $post->post_password ) ) {
		/** This filter is documented in wp-includes/post-template.php */
		return apply_filters( 'post_password_required', false, $post );
	}

	if ( ! isset( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] ) ) {
		/** This filter is documented in wp-includes/post-template.php */
		return apply_filters( 'post_password_required', true, $post );
	}

	require_once ABSPATH . WPINC . '/class-phpass.php';
	$hasher = new PasswordHash( 8, true );

	$hash = wp_unslash( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] );
	if ( ! str_starts_with( $hash, '$P$B' ) ) {
		$required = true;
	} else {
		$required = ! $hasher->CheckPassword( $post->post_password, $hash );
	}

	/**
	 * Filters whether a post requires the user to supply a password.
	 *
	 * @since 4.7.0
	 *
	 * @param bool    $required Whether the user needs to supply a password. True if password has not been
	 *                          provided or is incorrect, false if password has been supplied or is not required.
	 * @param WP_Post $post     Post object.
	 */
	return apply_filters( 'post_password_required', $required, $post );
}