Remove Protected Posts from Search Results in WordPress

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 😉


/** 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 😀


Hire WordPress exportsLoading comments...

Leave a comment

Your email address will not be published. Required fields are marked *