Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

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.

share|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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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