In WordPress, you can hide the content of a post by setting a password for it. Visitors are required to enter a password to continue reading the post content. This feature is useful in some situation, for example: you have a membership website, you create a password protected post and want to send it to your selected members only, so public users can't read it. In this case, you need to hide the post in the WordPress loops to make it not listed in the Blog page or other archive pages. In this post, I will show you how to do that with a simple code snippet.
To hide password protected posts from WordPress loops, we will hook to pre_get_posts
action which fires before querying the database to get posts. This hook allows us to modify the query by adding, removing conditions. We will use it to tell WordPress to exclude password protected posts.
The code snippet is quite simple:
add_action( 'pre_get_posts', 'prefix_exclude_password_protected_posts' ); function prefix_exclude_password_protected_posts( $query ) { if ( ! $query->is_singular() && ! is_admin() ) { $query->set( 'has_password', false ); } }
Note that in the snippet, we need to check to run the code only if we're not in the admin area or in a singular page (e.g. when viewing the post).
Personally I think password protection feature is not used widely, but it can be. Prividing premium content for membership website is a simple example. You can do more by using it for hidden part of your website. If you find this post or password protection is useful, please let me know in the comment.
Leave a Reply