Modify password protected page and show error message on wrong password

- 11/04/2020 10:51 AM

Files 1

php-file.php
php
function my_password_form() {
    global $post;

    $attempted     = $_SESSION['pass_attempt'] ?: false;
    $label         = 'pwbox-' . ( empty( $post->ID ) ? rand() : $post->ID );
    $wrongPassword = '';

    // If cookie is set password is wrong.
    if ( isset( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] ) && $attempted !== $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] ) {
        $wrongPassword = '<span style="color:#00000;font-weight:bold;">The password you have entered is invalid.</span>';
        // Store attempted password for comparison.
        // So we can show invalid password message only once.
        $_SESSION['pass_attempt'] = $_COOKIE[ 'wp-postpass_' . COOKIEHASH ];
    }
	
    $form = '<div class="password_before"><form action="' . esc_url( site_url( 'wp-login.php?action=postpass', 'login_post' ) ) . '" method="post">
   <input name="post_password" id="' . $label . '" type="password" size="20" maxlength="20" /><p>' . $wrongPassword . '</p>
    </form></div>';

    return $form;
}
add_filter( 'the_password_form', 'my_password_form' );

add_action(
    'wp_loaded',
    function() {
        if ( isset( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] ) ) {
            // Start session to compare pass hashs.
            session_start();
        }
    }
);