Redirect based on user and current page functions.

2019-09-20 02:17发布

I'm looking for a piece of code to add to my wordpress site to redirect certain users based on their role but only when they get to a certain page.

I need this to show a specific page to a specific user role and not the one others get. A plugin won't do in my scenario.

I'm not just looking for a redirect in php. I need to make something that will work in 3 steps:

First I need to check if the user/visitor is on the desired page.

After that I need to check for a specific user role (I got this covered).

And at last to redirect (got that coverd to).

I have no idea how to accomplish the first step inside the functions.php and if my flow even makes sense..

Edit: Solved!

add_action('template_redirect', 'redirect_user_role'); 

function redirect_user_role()
{ 
    if(current_user_can('subscriber') && is_page(' ID, Slug or name here ')) 
    { 
        wp_redirect('https://www.example.nl'); 
    } 
}

1条回答
Viruses.
2楼-- · 2019-09-20 02:34

First you need to get role of user,

  <?php
    global $current_user, $wpdb;
    $role = $wpdb->prefix . 'capabilities';
    $current_user->role = array_keys($current_user->$role);
    $role = $current_user->role[0]; //user role
    $page_title = $post->post_title; //get title  f page
    if($role=='subscriber' &&  $page_title=="aboutus") // compare
    { 
         wp_redirect('http://www.google.com'); //navigate if so
    }
   ?>
查看更多
登录 后发表回答