Hack: Password Protected Post With Custom Text

After yesterday’s post, I got to thinking that it would be useful to be able to customize the password protection text on a per-post basis. So not every password-protected post has the same exact same “This content is password protected…” replacement. Sp here is an alternative to that code that also looks for the custom field password_text. If found, then it will replace the standard text with whatever you put in that custom field.

add_filter('the_content', 'wpfilter_password_protected_message');
function wpfilter_password_protected_message($content) {
	global $post;
	if (!empty($post->post_password)) {
		$custom_fields = get_post_custom($post->ID);
		if ($custom_fields['password_text'][0]) {
			$content = str_replace('This content is password protected. To view it please enter your password below:',$custom_fields['password_text'][0],$content);
		}
	}
	return $content;
}

I like that this code also gives you the option to use the default text. All you need to do is simply not include the custom field in the post at all. Alternatively, you could have an else statement after the second if that uses a different str_replace to make your own default text.

Like the code from yesterday, this is dependent on the default WordPress text being exactly what you have in the code. If it ever changes, you’ll need to update that line.

Leave a Reply

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