我是wordpress的新手,如果他们在我的网站中输入以某个网址开头的特定位置,我想重定向用户登录。
e.g。如果他们输入以https://mysite/people
所以强制登录
https://mysite/people/
https://mysite/people/home
https://mysite/people/about
https://mysite/people/*
< - 以
我不确定如何在WP中这样做。
我已尝试插入wp-force-login
,但它已应用于整个网站。我在维基上看到的例子
/**
* Filter Force Login to allow exceptions for specific URLs.
*
* @return array An array of URLs. Must be absolute.
*/
function my_forcelogin_whitelist( $whitelist ) {
// Get visited URL without query string
$url_path = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
// Whitelist URLs
if ( '/page-name/' === $url_path ) {
$whitelist[] = site_url($_SERVER['REQUEST_URI']);
}
if ( '/page-name.php' === $url_path ) {
$whitelist[] = site_url($_SERVER['REQUEST_URI']);
}
return $whitelist;
}
add_filter('v_forcelogin_whitelist', 'my_forcelogin_whitelist', 10, 1);
如果他们输入任何仅以https://mysite/people
答案 0 :(得分:1)
使用template_redirect
过滤器。如果未登录的用户访问此页面,他们将被重定向到WordPress登录页面。
function my_page_template_redirect() {
$url_path = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
if( strpos($url_path, '/people/') !== 0 && ! is_user_logged_in() )
{
wp_redirect( wp_login_url() );
die;
}
}
add_action( 'template_redirect', 'my_page_template_redirect' );
答案 1 :(得分:1)
让我们来看看您的示例代码:
/**
* Filter Force Login to allow exceptions for specific URLs.
*
* @return array An array of URLs. Must be absolute.
*/
function my_forcelogin_whitelist( $whitelist ) {
// Get visited URL without query string
$url_path = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
// Whitelist URLs
if ( '/page-name/' === $url_path ) {
$whitelist[] = site_url($_SERVER['REQUEST_URI']);
}
if ( '/page-name.php' === $url_path ) {
$whitelist[] = site_url($_SERVER['REQUEST_URI']);
}
return $whitelist;
}
add_filter('v_forcelogin_whitelist', 'my_forcelogin_whitelist', 10, 1);
第一个命令将删除页面查询(例如:?name=john
)。因此,如果您访问https://mysite/people/<sub-page1>/<sub-page2>?foo=bar
之类的网址,则$url_path
为/people/<sub-page1>/<sub-page2>
。
如果您想将所有people
的子页面(https://mysite/people/*
)设置为黑名单,则表示开头不包含$url_path
的所有/people/
将成为$white_list
。
您可以通过strpos检查。
以下是完成的代码:
/**
* Filter Force Login to allow exceptions for specific URLs.
*
* @return array An array of URLs. Must be absolute.
*/
function my_forcelogin_whitelist( $whitelist ) {
// Get visited URL without query string
$url_path = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
// Whitelist URLs
// check if url_path is not /people + /...
// at to white list
if (strpos($url_path, '/people/') !== 0) {
$whitelist[] = site_url($_SERVER['REQUEST_URI']);
}
return $whitelist;
}
add_filter('v_forcelogin_whitelist', 'my_forcelogin_whitelist', 10, 1);
希望这有帮助!