Remove Protected Posts from Search Results in WordPress
I recently came up with a scenario on a website I created using WordPress which needed me to prevent protected posts from displaying in search results or on the blog index page. Initially, I thought this would be a setting on a per post page but alas, WordPress does not have the feature built-in.
After much research I found that one could actually remove protected posts entirely before the query actually took place (read: nice and efficient). To do so, I just had to pop the following code into my functions.php theme file and immediately got to watch my protected posts actually being protected from the public eye ;)
<?php /\*\* insert at end of functions.php \*\*/ // Filter to hide protected posts function exclude\_protected($where) { global $wpdb; return $where .= " AND {$wpdb->posts}.post\_password = '' "; } // Decide where to display them function exclude\_protected\_action($query) { if( !is\_single() && !is\_page() && !is\_admin() ) { add\_filter( 'posts\_where', 'exclude\_protected' ); } } // Action to queue the filter at the right time add\_action('pre\_get\_posts', 'exclude\_protected\_action'); ?>Let me know if you implement this code and how it works for you. Would love to see it in action :D