How to exclude password protected posts from WordPress loop

Exclude password protected posts from WordPress posts list or loop is using the filter function that is “post_where”

post_where filter for use exclude password protected posts from loop

This filter applies to the posts where clause and allows you to restrict which posts will show up in various areas of the site. Combined with restrict_manage_posts it allows you to only show posts matching specific conditions.

example:


add_filter( 'posts_where' , 'posts_where_function' );

function posts_where_function(){
// code goes here
}

Normally WordPress loop display all posts in the loop but we need to exclude some of private for password posts loop those are not shown to anonymous user or public. Problem have_posts() search all posts on posts table based on query args so we call the post_type = posts is query args it searches the entire wp_posts table and displays the specific posts_type related posts.

Exclude password protected posts WordPress loop or have_posts()

Here is an example to exclude password form posts loop


function exclude_post_filter( $where = '' ) {
// Make sure this only applies to loops / feeds on the frontend
if (!is_single() && !is_admin()) {
// exclude password protected
$where .= " AND post_password = ''";
}
return $where;
}
add_filter( 'posts_where', 'exclude_post_filter' );

simply copy above code and paste at the end of functions.php file and refresh your loop posts pages

Amazing you have removed password protected posts from loop list.

But remember one thing when using this code in functions.php it excludes all password protected posts from all another WordPress loops in the project.

start a project with us