X

How to Include Password Protected Posts in Search Results

Snippets by IsItWP

Are you looking for a way to include password protected posts in the search results of your website? While password protected posts are only visible to logged in users, we have created a quick code snippet that you can use to display password protected posts in search results to everyone including users that are not logged in.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

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;
}

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 27 best WordPress business themes for your website and 43 best photography themes for WordPress.

Comments   Leave a Reply

  1. Very nice, it’s just I wanted

  2. Daily Tip: How to Show Password-Protected Posts in WordPress Search Results October 17, 2011 at 1:03 pm

    […] tip comes to your courtesy of WPsnipp.com. Many thanks to Kevin Chard for posting this code. I tested it and it works as expected. Check out […]

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!