When password protecting a post in WordPress, the default text is often not quite right. In this quick tip, you'll learn how to easily change the password protected message in WordPress.
Note that he following tutorial teaches you how to change the text as a plugin, however, the main code can be simply added to your theme's functions.php
file instead.
Step 1
You should create a new folder in your WordPress site's plugins directory, and give it a title - I'll call it protected-text
.
Step 2
Create a new file, called protected-text.php
and add the following plugin information to the file:
<?php /* Plugin Name: Password Protected Text Plugin URI: http://code.tutsplus.com Description: This plugin changes the default password protected text. Version: 1.0 Author: code.tutsplus.com Author URI: http://code.tutsplus.com */
This text simply tells WordPress about the plugin, and ensures that it displays in the Plugins page in the WordPress admin.
Step 3
The first section of code checks to see if the post is password protected, and if there's already a cookie stored from a previous successful login.
function password_protected_change( $content ) { global $post; if ( ! empty( $post->post_password ) && stripslashes( $_COOKIE['wp-postpass_'.COOKIEHASH] ) != $post->post_password ) {
Step 4
If the post is password protected, and there isn't already a cookie, the password form is output. This plugin overwrites the whole password protected function, so we need to add the form as well as our new message.
You can add your main message in the space where I've written "Add your custom message!", and the label for the password field in the label for="post_password"
section.
$output = ' <form action="' . get_option( 'siteurl' ) . '/wp-pass.php" method="post"> '.__( "Add your custom message!" ).' <label for="post_password">Password:</label> <input name="post_password" class="input" type="password" size="20" /> <input type="submit" name="Submit" class="button" value="' . __( "Submit" ) . '" /> </form> '; return $output; }
Step 5
There's also an else statement, so that if the post isn't password protected, or there's already a cookie, it knows what to do. In this case, it'll simply display the post content.
} else { return $content; }
Step 6
The final step is to tell WordPress to use our new function when loading any content. This can be achieved with a simple add_filter
command.
add_filter( 'the_content','password_protected_change' );
In Summary
That's it - you've now made a simple plugin to overwrite the standard password protected form! You can download the source code for this project above.
If you have any questions, please feel free to leave a comment below.
Comments