I'm building a Wordpress-site, 开发者_如何学Cwhere user needs to log in before access to the blog itself. For now, I've used this:
add_action('wp_head','foofunc');
function foofunc() {
if(!is_user_logged_in()) die();
}
However, this way I cannot redirect the user to another url, as output has already started. Is there any way to redirect not-logged-in users to an url?
I would user init
but that redirects users in wp-admin too.
Martti Laine
Use the "init" handler together with is_admin() to check if the user is already in the admin panel or not:
add_action('init','foofunc');
function foofunc() {
$isLoginPage = strpos($_SERVER['REQUEST_URI'], "wp-login.php") !== false;
if(!is_user_logged_in() && !is_admin() && !$isLoginPage) {
header( 'Location: http://yourdomain.com/login' ) ;
die();
}
}
This was a turnkey solution that worked right out of the box for us.
http://wordpress.org/extend/plugins/more-privacy-options/
- you could use the s2member plugin. It creates 4 user levels the first level is for free users. When you create a page, you can pick a S2Member userlevel requirement for that pages.
- http://www.rlmseo.com/blog/require-login-for-wordpress-pages/ create a page-password-protect template that follows the format in that link. Apply the template to pages you want password protected.
- you could write a function that checks to see if a user is logged in on pages using *is_user_logged_in()*, *is_admin()* and *is_page()* and then redirects. make that function an action. Then hook that action into init. (I'm a little fuzzy if init is the right hook, but your redirect won't happen if any output has been sent to the screen)
Cleanest implementation:
if( (!is_user_logged_in()) && ($GLOBALS['pagenow'] !== 'wp-login.php') ) {
wp_redirect('http://anothersite.com');
}
Can be placed as is in functions.php
精彩评论