已登录用户的有条件主页

时间:2020-06-25 作者:Nayan Chowdhury

当用户登录并具有特定角色时,我想将wordpress站点的主页url更改为另一个url。这可能吗?

提前谢谢。

2 个回复
SO网友:Tim

你认为主页是什么?

是否要更改上的答案/ 您网站上的url?

如果是这样,我认为您可以使用init 挂钩和使用wp_redirect() 函数可根据wp_get_current_user() 后果

像这样的。

add_action(\'init\', function () {
    if ($user = wp_get_current_user()) {
        if (in_array(\'my-custom-role\', $user->roles)) {
            wp_redirect(\'/my-custom-url\');
        }
    }
});

SO网友:Ampersarnie

是的,这绝对是可能的。您需要采取几个步骤来实现这一目标;

检查用户当前是否在首页,您可以使用is_front_page 函数,您可能需要使用is_home 或者两者都可以,具体取决于您的配置和要求检查用户当前是否已登录,您可以使用is_user_logged_in 函数检查它们是否正确wp_get_current_userwp_safe_redirect 这将确保您重定向到的url是属于您的站点的url然后在init 钩子可以确保某些方法和数据可用,例如当前用户,并允许尽快进行重定向。

完整示例如下所示:

function redirect_from_front_page() {
    $redirect_url  = \'/example/url\'; // Change this to the path or url you wish to redirect to.
    $expected_role = \'custom-role\'; // Change this to the role you would like to redirect based on.
    
    /**
     * Check that the user is on the front page
     * before continuing.
     */
    if( ! is_front_page() ) {
        return;
    }

    /**
     * Check that the user is logged in.
     */
    if( ! is_user_logged_in() ) {
        return;
    }
    
    /**
     * Get the currect user roles.
     */
    $user  = wp_get_current_user();
    $roles = $user->roles;
    
    /**
     * If the user has a role that matches the expected role
     * redirect to the given page.
     */
    if ( in_array( $expected_role, $roles ) ) {
        wp_safe_redirect( $redirect_url );
        exit;
    }
}

add_action( \'init\', \'redirect_from_front_page\' ); 

相关推荐

static array on functions.php

在函数中。php中,我想访问数据库一次,以获取一个ACF对象,然后在本地“保存”它,以防止对数据库的进一步请求。我想首先在“init”钩子中调用以下函数。然后,假设,当我在以后的挂钩上调用它时,由于使用了“static”关键字,$current\\u store var已经设置好了,函数将在第一个“if”返回已经保存的静态var时停止。它不起作用-当访问稍后挂钩上的函数时,“isset($current\\u store)”返回false。我做错了什么?function get_current_store