Seagyn Davis
Remove Protected Posts from Search Results in WordPress

Remove Protected Posts from Search Results in WordPress

Reading time of post 1 min readDate when post was published2 April 2014
Disclosure: Some of the links in this post are affiliate links, meaning that if you click on one of the links and purchase an item, I may receive a commission. All opinions however are my own and I do not accept payments for positive reviews. This is just a little way for me to monetize the time I spend writing for you.

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

The following companies make my life awesome, maybe they'll make yours awesome too?