Admin Area

Set Default Visibility To Password Protected

In a recent project I had to make a certain post type to be password protected by default. Making posts password protected is default functionality that is built into WordPress core. To change the post to be password protected you do this in the publish settings on the edit post screen.

There is a visibility setting where you can click on the edit button and the a dropdown will appear with the choices Public, Private or Password protected.

password-protect

As this custom post type would always be password protected we needed to find a way of password protecting every page by default. This meant adding a bit of Javascript to the page to expand the visibility dropdown and select the password protected option.

There is an action that is used when the publish meta box is added to the page, so we can use this to add some Javascript to the page, the action we are going to use is post_submitbox_misc_actions. The first we do is check that the current post type is the protected post that we need. If it isn't the protected post type then we can just return out of the function, then we can add the jQuery code to set the password protected field by default.

// Force page to be password protected
add_action('post_submitbox_misc_actions', 'pu_change_visibility_default_to_password');

function pu_change_visibility_default_to_password()
{
    global $post;
		
    // Only change password for preview videos		
    if($post->post_type != 'protected-post')
    {
        return false;
    }
    ?>

    <script type="text/javascript">
        (function($){
            try {
                // Set the default text
                $('#post-visibility-display').text('Password Protected');

                // Set hidden post visibility value
                $('#hidden-post-visibility').val('password');

                // Check the radio button
                $('#visibility-radio-password').prop('checked', true);

                // Open the visibility display
                $('#post-visibility-select').show();
            } catch(err){}
        }) (jQuery);
    </script>

    <?php
}
Back to top

Fastest WordPress Hosting With WPEngine

Stunning speed, powerful security, and best-in-class customer service. At WP Engine.

Risk free for 60 days