I have a Wordpress website with 2 different pages that are protected using the native Wordpress password protect functionality.
I am looking for a way (if one exists) to customize the text above the password field differently for different password-protected pages.
I found a plugin that replaces the default text with custom HTML code, but then this message displays for ALL password protected pages.
What I'm trying to achieve is for password-protected page A to show "Message A" above the password field, and password-protected page B to show "Message B" above the password field, whereas currently all password-protected pages display the same message.
Does anyone know if there is a way to achieve this result? Thanks in advance!
Hook into the_password_form
filter and write your own custom password form as a variation of the default one. Then you can add any custom logic you want like detecting the page and outputting a different message.
In my example I am using is_page()
to determine the page but you could use any logic here you want.
function my_custom_password_form() {
global $post;
// custom logic for the message
$password_form_message = is_page('Private Page One') ?
__( "MESSAGE FOR ONE PAGE... This post is password protected. To view it please enter your password below:" ) :
__( "MESSAGE FOR ANOTHER PAGE... This post is password protected. To view it please enter your password below:" );
// put together the custom form using the dynamic message
$label = 'pwbox-'.( empty( $post->ID ) ? rand() : $post->ID );
$form = '<form class="protected-post-form" action="' . get_option('siteurl') . '/wp-pass.php" method="post">
' . $password_form_message . '
<label for="' . $label . '">' . __( "Password:" ) . ' </label><input name="post_password" id="' . $label . '" type="password" size="20" /><input type="submit" name="Submit" value="' . esc_attr__( "Submit" ) . '" />
</form>
';
return $form;
}
add_filter( 'the_password_form', 'my_custom_password_form' );
It is possible.
Yo have to add this code to your functions.php :
add_filter( 'the_password_form', 'custom_password_protected_form' );
function custom_password_protected_form($output) {
global $post;
switch ($post->post_name) {
case 'page-a':
$replacement_text = 'Message A';
break;
case 'page-b':
$replacement_text = 'Message B';
case 'default':
$replacement_text = '';
}
if (!empty($replacement_text)) $output = str_replace(__( 'This content is password protected. To view it please enter your password below:' ), $replacement_text, $output);
return $output;
}
Tested on WP 5.2.2