简体   繁体   English

访问页面时根据用户角色重定向 WordPress 用户

[英]Redirect WordPress User based on user role when accessing a page

I'm trying to create a simple redirect when someone tries accessing a certain page depending on user role.当有人尝试根据用户角色访问某个页面时,我正在尝试创建一个简单的重定向。

I've created a site with membership functionality that offers certain things to paid members.我创建了一个具有会员功能的网站,为付费会员提供某些东西。 Free members can only access one page after login but if they know the URL to the paid area they can see the content.免费会员登录后只能访问一个页面,但如果他们知道付费区的 URL,他们就可以看到内容。 I was wondering if there's a way to create a 301 redirect so that when the free member tries to go on the paid page, it redirects them back to the free area.我想知道是否有办法创建 301 重定向,以便当免费会员尝试进入付费页面时,它会将他们重定向回免费区域。

Is this possible?这可能吗? If you need more info, please ask!如果您需要更多信息,请询问!

Thanks David谢谢大卫

paste this code into your activate theme or chilled theme function.php file将此代码粘贴到您的激活主题或冷藏主题 function.php 文件中

function role_redirections() {
    $logedin_user = wp_get_current_user();  
    if (!is_user_logged_in() || !in_array( 'shop_manager', (array) $logedin_user->roles )) {
        $location1 =  home_url();
        header('Location: '.$location1.'');
    } 
}
add_action('wp_head', 'role_redirections');

@rajat.gite @rajat.gite

I tried you answer but it didn't quite work how I wanted so I modified the code as below:我试过你的回答,但它并没有像我想要的那样工作,所以我修改了代码如下:

function role_redirections() {
$loggedin_user = wp_get_current_user();  
if (!is_user_logged_in() || !in_array( 'memorial_user', (array) $loggedin_user->roles )) {
    $location1 =  'https://www.myswansong.com/member-portal/';
    header('Location: '.$location1.'');
    } 
}
add_action('wp_head', 'role_redirections');

The only real difference is amending the home_url();唯一真正的区别是修改 home_url(); to a string with the full URL I need.到一个带有我需要的完整 URL 的字符串。

Thanks for your help.谢谢你的帮助。

You can also try like this and make it more wordpress friendly.你也可以这样尝试,让它对 wordpress 更友好。

function role_redirections() {
$loggedin_user = wp_get_current_user();  
if (!is_user_logged_in() || !in_array( 'memorial_user', (array) $loggedin_user->roles )) {
    $location1 =  get_option( 'siteurl' ) .'/member-portal/';
    header('Location: '.$location1.'');
    } 
}
add_action('wp_head', 'role_redirections');

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

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