How to Include Password Protected Pages in WordPress Search Results

So by default, WordPress doesn’t include Password Protected pages in the list of search results. This is probably by design, to help keep prying eyes away from posts and pages that admins don’t want others to see. There are instances, though, where you might want this. One such example would be for a Patient Search type application, where Doctors could post potentially sensitive information about a patient and not want just anyone to see that info…but still want the client to be able to search for their information. An actual instance arose, for me, on a site where my client wanted to password protect photo galleries of their customers so that not just anyone could see their photos, but they could still use the built in search functionality of WordPress to search for their photos, and then enter the password to view them.

All we need to do is add this handy bit of code to our functions.php file:

// include password protected pages in search results

add_filter( 'posts_search', 'include_password_posts_in_search' );
function include_password_posts_in_search( $search ) {
global $wpdb;
if( !is_user_logged_in() ) {
$pattern = " AND ({$wpdb->prefix}posts.post_password = '')";
$search = str_replace( $pattern, '', $search );
}
return $search;
}

Thanks to WPMU.org for coming up with this solution, though their code had some errors in it that prevented it from actually working. The above should be all good to go!

Up Next: Three Ways to Simplify Your CSS3 Lifestyle