Using WordPress ‘get_the_password_form()’ PHP function

The get_the_password_form() WordPress PHP function retrieves the content of a protected post password form.

Usage

get_the_password_form($post);

Custom example:

echo get_the_password_form($my_post);

Parameters

  • $post (int|WP_Post) – Optional. Post ID or WP_Post object. Default is global $post.

More information

See WordPress Developer Resources: get_the_password_form()

Examples

Basic usage

Display the default password form for a protected post.

if (post_password_required()) {
    echo get_the_password_form();
}

Custom form for a specific post

Display a custom password form for a specific post.

function custom_password_form($post_id) {
    if (post_password_required($post_id)) {
        echo get_the_password_form($post_id);
    } else {
        the_content();
    }
}

custom_password_form(123);

Add a custom message to the password form

Add a custom message to the password form using a filter.

function my_password_form($output) {
    $custom_message = "<p>Please enter the password to view this post:</p>";
    return $custom_message . $output;
}

add_filter('the_password_form', 'my_password_form');

Modify the password form styling

Modify the password form input and button styling using a filter.

function custom_password_form_style($output) {
    $output = str_replace('type="password"', 'type="password" style="border: 1px solid #ccc; padding: 5px;"', $output);
    $output = str_replace('type="submit"', 'type="submit" style="background-color: #0073aa; color: #fff; border: none; padding: 5px 10px;"', $output);
    return $output;
}

add_filter('the_password_form', 'custom_password_form_style');

Remove the label from the password form

Remove the label from the password form using a filter.

function remove_password_form_label($output) {
    $output = preg_replace('/<label.*<\/label>/', '', $output);
    return $output;
}

add_filter('the_password_form', 'remove_password_form_label');