You are currently viewing Display the error message to users when enter wrong password on a password-protected Page (Solved)

Display the error message to users when enter wrong password on a password-protected Page (Solved)

In this article, I’ll answer the question to display the error message to users when enter wrong password on a password-protected Page. By default behaviour of the WordPress on the password-protected page doesn’t show any error message if you enter the wrong password into the password field. I was finding the solution but after reading lots of articles and the youtube research I found a way that really helpful and actually work to add error message on password protected page.

Code To Display the error message to users when enter wrong password on a password-protected Page (Solved)

On the function.php file add this code to add an error message on password protected page:

add_filter( 'the_password_form', 'wpse_12172023_custom_post_password_wrong_msg' );

/**
 * Add a message to the password form.
 *
 * @wp-hook the_password_form
 * @param   string $form
 * @return  string
 */
function wpse_12172023_custom_post_password_wrong_msg( $form )
{
    // No cookie, the user has not sent anything until now.
    if ( ! isset( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] ) ) {
        return $form;
    }

    // The refresh came from a different page, the user has not sent anything until now.
    if ( wp_get_raw_referer() != get_permalink() ) {
        return $form;
    }

    // Translate and escape.
    $msg = esc_html__( 'Oops! Looks like your password is incorrect. Just ask your proctor for the right one.', 'your_text_domain' );

    // We have a cookie, but it doesn’t match the password.
    $msg = "<p class='custom-password-message'>$msg</p>";
	?>
<style>
    .custom-password-message {
        background-color: #ff9999; /* Custom background color */
        color: #990000; /* Custom text color */
        padding: 10px; /* Custom padding */
        border: 1px solid #cc0000; /* Custom border */
        margin-bottom: 20px; /* Custom margin */
    }
</style>
<?php

    return $msg . $form;
}

That’s it!

Hope you will find this code helpful in solving the issue of displaying the error message to users when enter the wrong password on a password-protected Page. If you are facing any error drop the comment below. Our professional team will give you the solution in a short turn.

Contact SKFreelancers Team

Join Us on Facebook

Leave a Reply