user6176114 user6176114 - 4 months ago 5
PHP Question

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

Answer

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

Learn more about this in Documentation, Getting the current user.

Comments