Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect if it's not certain user - wordpress

Tags:

php

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

like image 217
user6176114 Avatar asked Oct 19 '22 05:10

user6176114


1 Answers

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;
}
like image 72
Panda Avatar answered Oct 29 '22 14:10

Panda