繁体   English   中英

WordPress:不在特定用户角色中时将主页和页面重定向到帐户页面

[英]WordPress: Redirect homepage and pages to account page when not in a specific user role

我想将 WordPress 中的每个页面(包括主页)重定向到特定页面。 但我也想设置一些例外。 我不想重定向的页面。 仅当当前用户不是用户角色“编辑”的一部分时,才应进行重定向。

例如:

我想将没有该角色的每个用户重定向到页面ID 为 9的页面。 但不应重定向ID 为 1、2、3 和 4的页面。

我设法将主页重定向到 ID 为 9 的页面。但只有主页。

但是我怎样才能将所有其他页面添加到该功能并添加例外? 我想我必须以某种方式将例外情况列入白名单,但我现在不明白。

编辑:这里有一些更多的背景:我有一个用户角色(在这个例子中是“编辑”),它有一个自己的成员区域。 现在我想限制每个用户和角色对整个站点的访问。 但是如果用户使用“编辑器”角色登录,我想允许他们在会员区导航。 但是如果用户没有登录,我需要登录页面和注册页面来为所有人打开。 其他所有内容都应重定向到登录页面(ID 9)。

这是当前代码:

function redirect_homepage() {
    if( ! is_home() && ! is_front_page() )
        return;

    wp_redirect( get_permalink('9') );
    exit;
}

add_action( 'template_redirect', 'redirect_homepage' );

我遇到您的编辑问题的方式:

  1. 您希望只有登录用户才能访问整个页面。
  2. 但是应该有可见的注册和登录页面,以便用户可以注册和登录。
  3. 这些页面是自定义页面(不是 wp-admin),并且您拥有页面的 ID。
  4. 只有具有“编辑”角色的登录用户才能使用整个页面。 如果您已登录,但没有“编辑”角色,您对页面的访问权限与未登录用户的访问权限相同(无访问权限/因此重定向到登录页面或其他)。

因此,您可以将代码放入主题的functions.php文件中:

<?php

function editors_only() {

    /* Redirect not logged in users */

    // instead of '12' and '13' you write the page ids of your login and register pages
    if ( !is_user_logged_in() && !is_page( 12 ) && !is_page( 13 ) ) {
        wp_redirect( get_permalink(12) ); // redirect to login page
        exit;
    }

    /* Redirect logged in users */

    if ( is_user_logged_in() ) {

        $user = wp_get_current_user(); // get current user
        $user_access = false; // set boolean for access to false
        if ( in_array( 'editor', (array) $user->roles ) ) {
            $user_access = true; // if user role correct set boolean to true
        }

        if ( $user_access == false ) { // is user has not the editor role
            wp_redirect( get_permalink(12) ); // redirect to login page
            exit;
        }
    }
}
add_action( 'wp', 'editors_only' ); 

?>

我认为这不是最佳做法,也不打算将您登录的用户重定向到您的登录页面,因为他们已经登录,但只是没有“编辑”角色。 也许您有一个upgrade account页面或此用户角色的其他页面。 您可以在“重定向未登录用户”代码(另一个&& !is_page(id) )中添加此页面 ID,如果用户访问为 false,则将此页面的 ID 放入get_permalink(id) function 中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM