0

Is there a way to force log-in even for viewing a WordPress blog that the blog's owner can turn on and off by themselves?

I can hardcode it in the template's header.php like so:

if ( !is_user_logged_in() ) {
   wp_redirect( wp_login_url() );
   exit;
}

but this can't be influenced from the blog's administration page.

There is the force user login plugin, but it doesn't work in 3.x blogs. I'll try to patch the plugin for 3.x, but suggestions for other (native?) methods are welcome.

2

This simple to implement, you could put this into functions.php if you want it tied to a theme, or else create your own plugin from this:

add_action('init','my_force_login');
function my_force_login(){
    if ( !is_user_logged_in() &&  !in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ) ) ) {
        $force_login=get_option('my_force_login');
        if($force_login){
            wp_redirect( wp_login_url() );
            exit;
        }
    }
}

For this to work you will then need to create an option (either a theme option if this is to be tied to a theme, or otherwise an extra option in an appropriate WordPress page.

In the above, I am assuming there is an option with name 'my_force_login' with value true/false (or 1/0) which determines if the redirect should take effect.

The redirect applies to all logged-out users to all pages except the login/register page.

| improve this answer | |
  • You can add custom options to the WP backend easily? Cool, wasn't aware of that. Thanks, I will try this out! – Pekka Feb 22 '12 at 10:53
  • 1
    Yup, see the Codex. The examples will be particularly helpful. – Stephen Harris Feb 22 '12 at 11:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.