-1

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'); 
    } 
}
Tristan .L
  • 829
  • 3
  • 9
  • 20

1 Answers1

1

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
    }
   ?>
Vasim Shaikh
  • 4,485
  • 2
  • 23
  • 52
  • This code seems to be perfect, however.. To make this fit the functions.php, shouldn't this be inside an action hook? And if so do you have any idea where what $tag to use? For example: `add_action('$tag', 'redirect_user_role');` – Tristan .L Jan 29 '16 at 08:36
  • add_action('template_redirect', 'hooker'); function hooker(){ //I load just before selecting and rendering the template to screen } – Vasim Shaikh Jan 29 '16 at 08:40
  • 1
    Final code I used: `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'); } }` – Tristan .L Jan 29 '16 at 09:09
  • are you get an output – Vasim Shaikh Jan 29 '16 at 09:11