简体   繁体   中英

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. 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.

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 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

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(); to a string with the full URL I need.

Thanks for your help.

You can also try like this and make it more wordpress friendly.

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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