Wordpress重定向用户仅在特定页面中登录

问题描述 投票:1回答:2

我是wordpress的新手,我想重定向用户,如果他们进入我的网站中以特定网址开头的特定位置,则会重新定位用户。

例如如果他们输入以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开头的页面,如何重新编写此代码以强制登录

php wordpress
2个回答
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
投票

我们来看看你的示例代码:

/**
 * 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/s将成为$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);

希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.