Showing the post password form for excerpts in WordPress

I recently came across an interesting situation that I had never thought about before. Many WordPress themes show excerpts on the front page and other archive-type views. When viewing a password-protected post, this message is displayed:

There is no excerpt because this is a protected post.

While this is fine for many scenarios, it may not be the most helpful piece of text for the average Internet user. Instead of showing the message, we’ll replace it with a password form.

Replacing the no excerpt text with a password form

WordPress comes packaged with a neat function called get_the_password_form() that handles most of the work for us. It generates the entire form. All we need to do is load it at the appropriate time.

Open your theme’s functions.php file and drop this code in:

<?php

add_filter( 'the_excerpt', 'excerpt_protected' );

function excerpt_protected( $content ) {
	if ( post_password_required() )
		$content = get_the_password_form();

	return $content;
}

?>

This will give us a new message:

This post is password protected. To view it please enter your password below:

Followed by that message is an input field for the post password.

Writing shorter tutorials

For those of you that follow this blog regularly, you know that I typically write long, in-depth tutorials. Many times, these are advanced techniques that not everyone will use. My plan is to start mixing in some quick tutorials that only take a few minutes to implement and maybe help out the average user more. This way, I can write more often. The longer tutorials tend to take a few days of work.

If you have any ideas for WordPress or bbPress tutorials, feel free to let me know in the comments or through my contact form.