Using WordPress ‘comment_on_password_protected’ PHP action

The comment_on_password_protected WordPress PHP action fires when a comment is attempted on a password-protected post.

Usage

add_action('comment_on_password_protected', 'your_function_name', 10, 1);

function your_function_name($comment_post_id) {
    // Your custom code here
}

Parameters

  • $comment_post_id (int): The ID of the password-protected post on which the comment is attempted.

More information

See WordPress Developer Resources: comment_on_password_protected

Examples

Redirect user to a custom page

Redirect the user to a custom page when they try to comment on a password-protected post.

add_action('comment_on_password_protected', 'redirect_to_custom_page', 10, 1);

function redirect_to_custom_page($comment_post_id) {
    wp_redirect('https://example.com/custom-page/');
    exit;
}

Display a custom message

Display a custom message when a user tries to comment on a password-protected post.

add_action('comment_on_password_protected', 'display_custom_message', 10, 1);

function display_custom_message($comment_post_id) {
    echo '<p>Please enter the password before leaving a comment.</p>';
}

Log comment attempts on password-protected posts

Log attempts to comment on password-protected posts.

add_action('comment_on_password_protected', 'log_comment_attempt', 10, 1);

function log_comment_attempt($comment_post_id) {
    error_log('Comment attempt on password-protected post ID: ' . $comment_post_id);
}

Send an email notification

Send an email notification to the admin when someone tries to comment on a password-protected post.

add_action('comment_on_password_protected', 'send_email_notification', 10, 1);

function send_email_notification($comment_post_id) {
    $admin_email = get_option('admin_email');
    $subject = 'Comment Attempt on Password-Protected Post';
    $message = 'Someone tried to comment on the password-protected post with ID: ' . $comment_post_id;
    wp_mail($admin_email, $subject, $message);
}

Disable comments on password-protected posts

Disable comments completely on password-protected posts.

add_action('comment_on_password_protected', 'disable_comments_on_protected_posts', 10, 1);

function disable_comments_on_protected_posts($comment_post_id) {
    wp_die('Comments are not allowed on password-protected posts.');
}