我的任务是创建一个WordPress站点,订阅者(由管理员注册)不知道后端。
我还必须这样做,在导航到任何页面时,如果用户没有登录,就会显示一个登录表单。登录后,应显示用户试图查看的页面。
我有以下代码whcih检测用户是否登录并向他们显示登录页面,但不幸的是,由于这需要重定向,因此显然无法将用户重定向到他们最初想要去的地方。
我想做的是检测usre是否已登录,以及它们是否未覆盖通常用于自定义的模板login.php
模板,类似于404模板的显示方式。
要做到这一点,我想我需要以某种方式连接到模板层次结构,并覆盖通常的模板,但我不确定具体如何实现这一点,并将听取任何提示。
这是我目前得到的信息,如果用户未登录,它会将用户重定向到特定页面(虽然很接近,但并不完美)-
/**
* Redirect the user to the \'please login\' page if they are not logged in
*/
add_action(\'wp\', \'djg_check_login\');
function djg_check_login(){
$scheme = (is_ssl()) ? \'https\' : \'http\';
/** Construct the URL of the page the user is trying to view */
$url = sprintf(
\'%1$s://%2$s%3$s\',
$scheme, /** %1$s - The request shceme (http|https) */
$_SERVER[\'SERVER_NAME\'], /** %2$s - The server name */
$_SERVER[\'REQUEST_URI\'] /** $3$s - The request URI */
);
/** List the pages that are authorised for non-logged in users */
$authorised_pages = array(
get_site_url().\'/login/\',
get_site_url().\'/wp-login.php\'
);
/** Ensure that the user is actually NOT logged in */
if(!is_user_logged_in()) :
/** Ensure we are not trying to view an $authorised page (to avoid a loop) */
if(!in_array($url, $authorised_pages)) :
/** Redirect the user and exit */
wp_safe_redirect(get_page_link(7));
exit;
endif;
endif;
}
最合适的回答,由SO网友:David Gard 整理而成
事实证明,使用template_include
过滤器-
/**
* Override the standard WordPress template with the \'please login\' template if the current user is not logged in
*/
add_filter(\'template_include\', \'portfolio_page_template\', 99);
function portfolio_page_template($template){
/** List the pages that are authorised for non-logged in users */
$authorised_pages = array(
get_site_url().\'/login/\',
get_site_url().\'/wp-login.php\'
);
/** Ensure that the user is actually NOT logged in */
if(!is_user_logged_in()) :
/** Ensure we are not trying to view an $authorised page (to avoid a loop) */
if(!in_array($url, $authorised_pages)) :
/** Setup the new template */
$new_template = locate_template(array(\'login-page.php\'));
if($new_template !== \'\') :
return $new_template ;
endif;
endif;
endif;
return $template;
}