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.
Very nice, it’s just I wanted
[…] 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 […]