user6176114
user6176114

Reputation: 321

Redirect if it's not certain user - wordpress

I have created a page for a certain user in wordpress. Let's say his username is John. I am looking for PHP script that allow only 'John' to access that page and if users with different username other than 'John' tries to access the page they are redirected to another page.

I am new to PHP, so here's some code I have tried. But it redirects all users, even the user with username 'John'

<?php $user_info = get_userdata(1);
  $username = $user_info->user_login;
if ( $username=='John' ) {
echo '';
} else {
wp_redirect( home_url() );
exit;
}
?>

Here's a wordpress page with parameters to get userdata - https://codex.wordpress.org/Function_Reference/get_userdata

Upvotes: 5

Views: 386

Answers (3)

Panda
Panda

Reputation: 6896

You can use wp_get_current_user() function instead.

global $current_user; 
get_currentuserinfo();
$username = $current_user->user_login;

if ( $username == 'John' ) {
    echo '';
} else {
    wp_redirect( home_url() );
    exit;
}

Upvotes: 2

Farrukh Faizy
Farrukh Faizy

Reputation: 1235

Try this : First check if user is logged_in if yes then take the user information and do what ever you want with it

if(is_user_logged_in()){
  $current_user = wp_get_current_user();
      if($current_user->user_login == "John"){
             wp_safe_redirect("Where ever you want");
             exit;
           }
      else
          wp_safe_redirect(home_url('/'));

NOTE : Make sure to check your username in database , I set my username as my lastname.

Upvotes: 0

Prafulla Kumar Sahu
Prafulla Kumar Sahu

Reputation: 9703

This may solve your problem.

add_action( 'init', 'blockusers_init' );
function blockusers_init() {
  global $current_user; 
  $current_user = wp_get_current_user();
  if ( 'John' == $current_user->user_login ) {
    //your desire page url
    wp_redirect( 'your page url' );
    exit;
  } else {
     wp_redirect( home_url() );
     exit;
  }
}

Take reference from

add_action( 'init', 'blockusers_init' );
function blockusers_init() {
  if ( is_admin() && ! current_user_can( 'administrator' ) &&
 ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
    wp_redirect( home_url() );
    exit;
 }
}

https://premium.wpmudev.org/blog/limit-access-to-your-wordpress-dashboard/

Upvotes: 1

Related Questions