How to Programmatically Assign a Password to Posts within a Date Range

Let’s say for whatever reason, you need to require a password with posts on your site within a certain date range.

In this example, we will examine posts that have been published before the current date.

To help us achieve this password protection, we need to hook into the post_password_required filter:

First off, let’s hook into the filter and make sure to match the parameters correctly:

function ian_sackofwits_filter_post_password_required( $required, $post ) { 

}; 
         
add_filter( 'post_password_required', 'ian_sackofwits_filter_post_password_required', 10, 2 ); 

Next we’re going to make a conditional that checks to see if the current date is after the published date of the post, and we will return the boolean that determines whether the original post should be password protected in the case that the published post is not in the past:

if ( (new DateTime())->format("Ymd") > get_the_date("Ymd",$post) ) 
{
   //TODO
}
return $required;

If the post was published in the past, we need to set the password, which in our case will just simply be the string ‘test’:

$post->post_password = "test";

And now we need to verify that the password that the user enters is the correct password.

The following code comes from the post_password_required function in the WordPress core, and it will allow us to verify that the password is correctly entered by the user:

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

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

Here’s the full complete code for programmatically enabling the password protection:

function ian_sackofwits_filter_post_password_required( $required, $post ) { 
	
	if ( (new DateTime())->format("Ymd") > get_the_date("Ymd",$post) ) 
	{
		$post->post_password = "test";
		
		require_once ABSPATH . WPINC . '/class-phpass.php';
		$hasher = new PasswordHash( 8, true );

		$hash = wp_unslash( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] );
		if ( 0 !== strpos( $hash, '$P$B' ) ) {
			$required = true;
		} 
		else {
			$required = ! $hasher->CheckPassword( $post->post_password, $hash );
		}
	}
	return $required;
}
         
add_filter( 'post_password_required', 'ian_sackofwits_filter_post_password_required', 10, 2 ); 

As always, add this code to your theme’s functions.php file or use a plugin such as Code Snippets.

Leave a comment

Your email address will not be published. Required fields are marked *