The post_password_required WordPress PHP filter determines if a post requires the user to provide a password.
Usage
add_filter('post_password_required', 'your_custom_function', 10, 2);
function your_custom_function($required, $post) {
// your custom code here
return $required;
}
Parameters
$required(bool) – Whether the user needs to supply a password. True if the password has not been provided or is incorrect, false if the password has been supplied or is not required.$post(WP_Post) – Post object.
More information
See WordPress Developer Resources: post_password_required
Examples
Make all posts password protected
Force password protection for all posts, regardless of their current settings.
add_filter('post_password_required', 'all_posts_password_protected', 10, 2);
function all_posts_password_protected($required, $post) {
return true;
}
Disable password protection for a specific post
Remove password protection for a specific post by its ID.
add_filter('post_password_required', 'disable_password_protection_for_post', 10, 2);
function disable_password_protection_for_post($required, $post) {
if ($post->ID == 123) {
return false;
}
return $required;
}
Enable password protection only for logged-in users
Allow only logged-in users to access password-protected posts.
add_filter('post_password_required', 'password_protection_for_logged_in_users', 10, 2);
function password_protection_for_logged_in_users($required, $post) {
if (is_user_logged_in()) {
return false;
}
return $required;
}
Require password for specific categories
Require a password for posts in specific categories.
add_filter('post_password_required', 'password_required_for_categories', 10, 2);
function password_required_for_categories($required, $post) {
$protected_categories = array('premium', 'exclusive');
$post_categories = wp_get_post_categories($post->ID);
foreach ($post_categories as $category) {
if (in_array($category->slug, $protected_categories)) {
return true;
}
}
return $required;
}
Set a default password for all password-protected posts
Override the post-specific passwords and set a global password for all protected posts.
add_filter('post_password_required', 'default_password_for_protected_posts', 10, 2);
function default_password_for_protected_posts($required, $post) {
$default_password = 'global_password';
if ($required && isset($_COOKIE['wp-postpass_' . COOKIEHASH]) && $_COOKIE['wp-postpass_' . COOKIEHASH] === $default_password) {
return false;
}
return $required;
}