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.

link|improve this question

67% accept rate
feedback

1 Answer

up vote 2 down vote accepted

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.

link|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 at 10:53
1  
Yup, see the Codex. The examples will be particularly helpful. – Stephen Harris Feb 22 at 11:21
feedback

Your Answer

 
or
required, but never shown

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